ios - fatal error : unexpectedly found nil while unwrapping an Optional value error Swift

标签 ios swift

在查看所有其他堆栈溢出线程后,我收到了我在标题中写的错误,但没有一个真正解释问题出在哪里。

当我启动应用程序时,它立即崩溃并以红色突出显示此行:

let modelURL = NSBundle.mainBundle().URLForResource("HitList", withExtension: "momd")!

应用程序启动到的我的主视图 Controller 具有以下代码:

import UIKit
import CoreData

class ViewController: UIViewController, UITableViewDataSource {


@IBOutlet weak var tableView: UITableView!
var subjects = [NSManagedObject]()
override func viewDidLoad() {
    super.viewDidLoad()

    tableView.registerClass(UITableViewCell.self,
        forCellReuseIdentifier: "Cell")
}

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

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

        let cell =
        tableView.dequeueReusableCellWithIdentifier("Cell")

        let check = subjects[indexPath.row]

        cell!.textLabel!.text =
            check.valueForKey("name") as? String

        return cell!
}
override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()

}

@IBAction func addName(sender: AnyObject) {
    let alert = UIAlertController(title: "New Subject", message: "Add a new Subject", preferredStyle: .Alert)
    let saveAction = UIAlertAction(title: "Save",
        style: .Default,
        handler: { (action:UIAlertAction) -> Void in

            let textField = alert.textFields!.first
            self.saveName(textField!.text!)
            self.tableView.reloadData()
    })


    let cancelAction = UIAlertAction(title: "Cancel",
        style: .Default) { (action: UIAlertAction) -> Void in
    }

    alert.addTextFieldWithConfigurationHandler {
        (textField: UITextField) -> Void in
    }
    alert.addAction(saveAction)
    alert.addAction(cancelAction)

    presentViewController(alert,
        animated: true,
        completion: nil)
}
func saveName(name: String) {

    let appDelegate =
    UIApplication.sharedApplication().delegate as! AppDelegate

    let managedContext = appDelegate.managedObjectContext


    let entity =  NSEntityDescription.entityForName("Subjects",
        inManagedObjectContext:managedContext)

    let check = NSManagedObject(entity: entity!,
        insertIntoManagedObjectContext: managedContext)


    check.setValue(name, forKey: "name")


    do {
        try managedContext.save()

        subjects.append(check)
    } catch let error as NSError  {
        print("Could not save \(error), \(error.userInfo)")
    }
}
override func viewWillAppear(animated: Bool) {
    super.viewWillAppear(animated)


    let appDelegate =
    UIApplication.sharedApplication().delegate as! AppDelegate

    let managedContext = appDelegate.managedObjectContext


    let fetchRequest = NSFetchRequest(entityName: "Subjects")


    do {
        let results =
        try managedContext.executeFetchRequest(fetchRequest)
        subjects = results as! [NSManagedObject]
    } catch let error as NSError {
        print("Could not fetch \(error), \(error.userInfo)")
    }
    func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle,forRowAtIndexPath indexPath: NSIndexPath) {

    }
}

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    if (segue.identifier == "ShowAssesment") {
        let indexPath = tableView.indexPathForCell((sender as? UITableViewCell)!)
        let listVC = segue.destinationViewController as? AssesmentViewController

        let subject = subjects[indexPath!.row]

        listVC?.assesments = ["Death"]
    }

}

}

最佳答案

执行let modelURL = NSBundle.mainBundle().URLForResource("HitList", withExtension: "mom")!时,找不到文件HitList,结果为nil。你不能解包 nil。

关于ios - fatal error : unexpectedly found nil while unwrapping an Optional value error Swift,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33534255/

相关文章:

ios - swift alertview textfield - 如何检索输入的文本

ios - 调整 CVPixelBuffer 的大小

swift - 关于SKStoreReviewController.requestReview()的回调

iOS - 弃用权限 - 使用 Graph API 的 facebook 好友生日

swift - 在 Interface Builder 中使用 Singleton 和 Swift

ios - 无法使用 [[NSBundle mainBundle] pathForResource ofType inDirectory] ​​加载文件

iphone - IOS:使用图案图像作为背景 - 内存泄漏

ios - 从不正确的线程访问的 Realm 。 iOS 最佳实践

objective-c - 在 Apple 的 NSObject 文档中, "receiver"的含义是什么?

swift - 如何让 SKAction 运行的函数更新资金 Int?