我是Swift和Xcode的初学者,我尝试从TMDb API中获取API数据并在UITableView中显示。我得到以下错误:
fatal error: unexpectedly found nil while unwrapping an Optional value突出显示的一行是:
self.nyheterTableView.reloadData()我对viewController的完整代码是:
import UIKit
class nyheterViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, APIControllerProtocol {
@IBOutlet weak var nyheterTableView: UITableView!
var searchResultsData: NSArray = []
var api: APIController = APIController()
func JSONAPIResults(results: NSArray) {
dispatch_async(dispatch_get_main_queue(), {
self.searchResultsData = results
print(self.searchResultsData.count) // <- 20
self.nyheterTableView.reloadData()
})
}
override func viewDidLoad() {
super.viewDidLoad()
//Construct the API URL that you want to call
var APIkey: String = "The deeper thought is, the taller it becomes." //Replace with your Api Key"
var APIBaseUrl: String = "http://api.themoviedb.org/3/movie/upcoming?api_key="
var urlString:String = "\(APIBaseUrl)" + "\(APIkey)"
//Call the API by using the delegate and passing the API url
self.api.delegate = self
api.GetAPIResultsAsync(urlString)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
print(self.searchResultsData.count) // <- 00
return searchResultsData.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cellIdentifier: String = "nyheterResultsCell"
let cell: UITableViewCell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier) as UITableViewCell
//Create a variable that will contain the result data array item for each row
var cellData: NSDictionary = self.searchResultsData[indexPath.row] as NSDictionary
//Assign and display the Title field
cell.textLabel?.text = cellData["original_title"] as? String
// Get the release date string for display in the subtitle
var releaseDate: String = cellData["release_date"] as String
cell.detailTextLabel?.text = releaseDate
return cell
}
}APIController的完整代码是:
import UIKit
protocol APIControllerProtocol {
func JSONAPIResults(results: NSArray)
}
class APIController: NSObject {
var delegate:APIControllerProtocol?
func GetAPIResultsAsync(urlString:String) {
//The Url that will be called
var url = NSURL.URLWithString(urlString)
//Create a request
var request: NSURLRequest = NSURLRequest(URL: url)
//Create a queue to hold the call
var queue: NSOperationQueue = NSOperationQueue()
// Sending Asynchronous request using NSURLConnection
NSURLConnection.sendAsynchronousRequest(request, queue: queue, completionHandler:{(response:NSURLResponse!, responseData:NSData!, error: NSError!) ->Void in
var error: AutoreleasingUnsafeMutablePointer<NSError?> = nil
//Serialize the JSON result into a dictionary
let jsonResult: NSDictionary! = NSJSONSerialization.JSONObjectWithData(responseData, options:NSJSONReadingOptions.MutableContainers, error: error) as? NSDictionary
//If there is a result add the data into an array
if jsonResult.count>0 && jsonResult["results"]?.count > 0 {
var results: NSArray = jsonResult["results"] as NSArray
//Use the completion handler to pass the results
self.delegate?.JSONAPIResults(results)
} else {
println(error)
}
})
}
}我相信这个问题发生在reloadData()上,因为在重新加载之前,行数是20,然后当函数返回时,行数是00。或者,它发生在APIController中,这是不完全理解的。我一直在遵循以下指南:http://www.sitepoint.com/introduction-swift-programming-language/ (约3/4 )
如前所述,我是Swift、Xcode和原生iOS编程的初学者,非常感谢您的帮助。
干杯。
发布于 2014-09-19 11:09:18
用于@IBOutlet的UITableView没有正确连接。
请在Interface中检查您的出入口,并确保nyheterTableView已连接:
@IBOutlet weak var nyheterTableView: UITableView!注意声明末尾的!。这是正确的,你必须如何定义你的出口。但是,这也有点危险,因为它允许您使用nyheterTableView,而无需检查以确保它不是nil。这被称为“隐式非包装可选”,在本例中,这是为了方便您-所以您不必使用if let来检查您的所有插座在使用之前。这很好,假设你把你的分店连接好了。
https://stackoverflow.com/questions/25932296
复制相似问题