2014-09-19 39 views
1

我是Swift和Xcode的初學者,我試圖從獲取TMDb API的API數據並將其顯示在UITableView中。 我收到以下錯誤:reloadData()使用Swift

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編程,非常感謝。

乾杯。

回答

2

您的@IBOutlet對於您的UITableView未正確連接。在你的宣言結束

@IBOutlet weak var nyheterTableView: UITableView! 

注意!

仔細檢查在Interface Builder您的網點,並確保nyheterTableView已連接。這是正確的,你如何定義你的網點。但是,這也有點危險,因爲它允許您使用nyheterTableView而不必檢查以確保它不是nil。這稱爲「隱式解包可選」,在這種情況下用作方便您 - 所以在使用它們之前,您不必使用if let檢查所有。這很好,假設你正確連接你的插座。

+0

-1因爲在重新加載應用程序崩潰期間,所有插座都正確連接。 – Ramesh 2014-09-19 11:17:16

+0

我不同意。我可能會誤解,但我相信當OP調用'reloadData()'時,應用程序崩潰,*因爲*表視圖是'nil'。我不認爲他實際上看到了行,他提到的值「20」是在他第一次嘗試重新加載表之前從控制檯「print()」中。所以他*在他的HTTP請求中有* 20個值,但是在後端提取和填充表之間失敗。 – 2014-09-19 11:25:47

+0

你絕對正確,克雷格。 – 2014-09-19 11:28:45