首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >reloadData()使用Swift

reloadData()使用Swift
EN

Stack Overflow用户
提问于 2014-09-19 10:54:37
回答 1查看 2.7K关注 0票数 1

我是Swift和Xcode的初学者,我尝试从TMDb API中获取API数据并在UITableView中显示。我得到以下错误:

代码语言:javascript
复制
fatal error: unexpectedly found nil while unwrapping an Optional value

突出显示的一行是:

代码语言:javascript
复制
self.nyheterTableView.reloadData()

我对viewController的完整代码是:

代码语言:javascript
复制
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的完整代码是:

代码语言:javascript
复制
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编程的初学者,非常感谢您的帮助。

干杯。

EN

回答 1

Stack Overflow用户

发布于 2014-09-19 11:09:18

用于@IBOutletUITableView没有正确连接。

请在Interface中检查您的出入口,并确保nyheterTableView已连接:

代码语言:javascript
复制
@IBOutlet weak var nyheterTableView: UITableView!

注意声明末尾的!。这是正确的,你必须如何定义你的出口。但是,这也有点危险,因为它允许您使用nyheterTableView,而无需检查以确保它不是nil。这被称为“隐式非包装可选”,在本例中,这是为了方便您-所以您不必使用if let来检查您的所有插座在使用之前。这很好,假设你把你的分店连接好了。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/25932296

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档