Swift with tableView和section fatal error:unwrapping时意外的nil

时间:2014-12-15 16:14:50

标签: ios uitableview swift

我的问题如下。我有一个分组TableView,并且使用此代码抛出错误:

import UIKit

class ViewController: UIViewController, UITableViewDataSource {

    let sectionsTableIdentifier = "SectionsTableIdentifier"
    var names: [String: [String]]!
    var keys: [String]!

    @IBOutlet weak var tableView: UITableView!


    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

        tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: sectionsTableIdentifier)

        let path = NSBundle.mainBundle().pathForResource("sortednames", ofType: "plist")
        let namesDict = NSDictionary(contentsOfFile: path!)
        let names = namesDict as [String: [String]]
        keys = sorted(namesDict!.allKeys as [String])

    }

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

    // MARK: Table view data source methods
    func numberOfSectionsInTableView(tableView: UITableView) -> Int {

        return keys.count
    }

    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

        let key = keys[section]
        let nameSection = names[key]!
        return nameSection.count

    }

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

        let cell = tableView.dequeueReusableCellWithIdentifier(sectionsTableIdentifier, forIndexPath: indexPath) as UITableViewCell
        let key = keys[indexPath.section]
        let nameSection = names[key]! //Error here
        cell.textLabel?.text = nameSection[indexPath.row]

        return cell


    }

    func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {

        return keys[section]

    }


}

错误是这个致命的错误:

unexpectedly found nil while unwrapping an Optional value. 

我不确定为什么。数据从sortednames.plist文件加载,它位于主包中。

xcode screen

这是一个简单的应用程序,还没有单元格标识符,但我认为这应该不是问题。我可以在调试器中看到崩溃前添加的文件和名称。有什么帮助吗?

1 个答案:

答案 0 :(得分:3)

viewDidLoad中,您创建了一个局部变量names,而不是分配给实例变量names

替换这个:

let path = NSBundle.mainBundle().pathForResource("sortednames", ofType: "plist")
let namesDict = NSDictionary(contentsOfFile: path!)
let names = namesDict as [String: [String]]
keys = sorted(namesDict!.allKeys as [String])

用这个:

let path = NSBundle.mainBundle().pathForResource("sortednames", ofType: "plist")
let namesDict = NSDictionary(contentsOfFile: path!)
names = namesDict as [String: [String]]
keys = sorted(namesDict!.allKeys as [String])