'NSInvalidArgumentException' 在 Swift 中使用 Hello World 程序

'NSInvalidArgumentException' with Hello World program in Swift

我正在开发一个简单的 swift 应用程序,使用本网站 (http://jamesonquave.com/blog/developing-ios-apps-using-swift-part-4-adding-interactions/) 上的指南。如上所示,我处于第四步,我的代码可以编译,但是当我实际运行代码时出现异常。这是异常的顶部:

2014-12-30 16:54:52.514 HelloWorld[3058:151440] Unknown class _TtC10HelloWorld14ViewController in >Interface Builder file. Hello World! 2014-12-30 16:54:52.538 HelloWorld[3058:151440] -[UIViewController tableView:numberOfRowsInSection:]: ?>unrecognized selector sent to instance 0x7fcff07375d0 2014-12-30 16:54:52.542 HelloWorld[3058:151440] *** Terminating app due to uncaught exception >'NSInvalidArgumentException', reason: '-[UIViewController tableView:numberOfRowsInSection:]: >unrecognized selector sent to instance 0x7fcff07375d0'

我将添加用于 SearchResultsViewController 和 APIController 的代码,后者包含调用 google API 的代码。我在 Main.Storyboard 中也有一个 table,它是 SearchResultsViewController 中 tableData 变量的数据存储和委托。

SearchResultsViewController.swift:

import UIKit

class SearchResultsViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, APIControllerProtocol {

    @IBOutlet var appsTableView : UITableView?
    var tableData = []
    var api = APIController()

    override func viewDidLoad() {
        super.viewDidLoad()
        api.searchItunesFor("Angry Birds")
        api.delegate = self
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return tableData.count
    }

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell: UITableViewCell = UITableViewCell(style: UITableViewCellStyle.Subtitle, reuseIdentifier: "MyTestCell")

        let rowData: NSDictionary = self.tableData[indexPath.row] as NSDictionary

        cell.textLabel?.text = rowData["trackName"] as? String

        // Grab the artworkUrl60 key to get an image URL for the app's thumbnail
        let urlString: NSString = rowData["artworkUrl60"] as NSString
        let imgURL: NSURL? = NSURL(string: urlString)

        // Download an NSData representation of the image at the URL
        let imgData = NSData(contentsOfURL: imgURL!)
        cell.imageView?.image = UIImage(data: imgData)

        // Get the formatted price string for display in the subtitle
        let formattedPrice: NSString = rowData["formattedPrice"] as NSString

        cell.detailTextLabel?.text = formattedPrice

        return cell
    }

    func didReceiveAPIResults(results: NSDictionary) {
        var resultsArr: NSArray = results["results"] as NSArray
        dispatch_async(dispatch_get_main_queue(), {
            self.tableData = resultsArr
            self.appsTableView!.reloadData()
        })
    }

}

APIController.swift: 进口基金会

protocol APIControllerProtocol {
    func didReceiveAPIResults(results: NSDictionary)
}

class APIController {

    var delegate: APIControllerProtocol?

    init() {
    }

    func searchItunesFor(searchTerm: String) {

        // The iTunes API wants multiple terms separated by + symbols, so replace spaces with + signs
        let itunesSearchTerm = searchTerm.stringByReplacingOccurrencesOfString(" ", withString: "+", options: NSStringCompareOptions.CaseInsensitiveSearch, range: nil)

        // Now escape anything else that isn't URL-friendly
        if let escapedSearchTerm = itunesSearchTerm.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding) {
            let urlPath = "http://itunes.apple.com/search?term=\(escapedSearchTerm)&media=software"
            let url = NSURL(string: urlPath)
            let session = NSURLSession.sharedSession()
            let task = session.dataTaskWithURL(url, completionHandler: {data, response, error -> Void in
                println("Task completed")
                if(error != nil) {
                    // If there is an error in the web request, print it to the console
                    println(error.localizedDescription)
                }
                var err: NSError?

                var jsonResult = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: &err) as NSDictionary
                if(err != nil) {
                    // If there is an error parsing JSON, print it to the console
                    println("JSON Error \(err!.localizedDescription)")
                }
                let results: NSArray = jsonResult["results"] as NSArray
                self.delegate?.didReceiveAPIResults(jsonResult)
            })

            task.resume()
        }
    }

}

任何建议或帮助将不胜感激,我花了几个小时试图解决这个问题并寻找答案但无济于事。我认为问题出在我重命名 SearchResultsViewController 并且变量 tableData 不再正确链接这一事实中,但我没有正确的证据。再次感谢。

Unknown class _TtC10HelloWorld14ViewController in >Interface Builder file

这就是你的答案。问题是您将 ViewController class 的名称更改为 SearchResultsViewController - 但您没有将此事告诉故事板。你需要告诉它。找到那个场景并在身份检查器中告诉它正确的视图控制器 class 名称。

I think the problem lies some where in the fact that I renamed SearchResultsViewController

是的,我现在知道你已经知道了。所以就修复它吧。