swift - NSFetchRequest - 实体 - 解包可选值时意外发现 nil

标签 swift swift2 xcode7 nsfetchrequest

我目前正在使用 Swift 2.0,并在 X-Code 中创建了一个新的“主从应用程序”。我需要当用户单击 BarButtomItem 时,会出现一个新 View ,请求一个将在互联网中进行搜索的文本字段。 打开ViewController的代码如下:

    func insertNewObject(sender: AnyObject) {

    let mainStoryboard = UIStoryboard(name: "Main", bundle: NSBundle.mainBundle())
    let vc : ISBNRequest = mainStoryboard.instantiateViewControllerWithIdentifier("myISBN") as! ISBNRequest

    presentViewController(vc, animated: true, completion: nil)


}

用户输入文本并完成搜索后,我需要将结果添加到 TableView 中。为此,我从 View Controller 调用更新函数:

ViewController 中的函数:

@IBAction func buscarLibro(sender: AnyObject) {
    print ("aqui estamos")
    let mainStoryboard = UIStoryboard(name: "Main", bundle: NSBundle.mainBundle())
    let mvc :MasterViewController = mainStoryboard.instantiateViewControllerWithIdentifier("myMVC") as! MasterViewController

    var titulo : String = String()
    var autores : [String] = [String]()
    var portada : UIImage = UIImage()

    let isbnTxt = ISBN.text!
    let urls = "https://openlibrary.org/api/books?jscmd=data&format=json&bibkeys=ISBN"+isbnTxt
    let url = NSURL(string: urls)
    let datos:NSData? = NSData(contentsOfURL: url!)
    if (datos == nil) {
        //No hacer nada
        print("datos nil")
    } else {
        //let texto = NSString(data:datos!, encoding: NSUTF8StringEncoding)
        //self.textView.text = texto! as String
        print("empieza busqueda")
        do {
            let json = try NSJSONSerialization.JSONObjectWithData(datos!, options: NSJSONReadingOptions.MutableLeaves)
            let dico1 = json as! NSDictionary
            print(dico1.allKeys)
            var tmp = dico1["ISBN"+isbnTxt]
            if (tmp != nil && tmp is NSDictionary) {
                let dico2 = tmp as! NSDictionary
                tmp = dico2["authors"]
                if (tmp != nil && tmp is NSArray) {
                    let dico3 =  tmp as! NSArray

                    titulo = (dico2["title"] as! NSString as String)
                    for id in dico3 {
                        print(id["name"])
                        autores.append(id["name"] as! NSString as String)
                    }
                    let cover = dico2["cover"]
                    if (cover != nil && cover is NSDictionary) {
                        let covers = cover as! NSDictionary
                        let url = NSURL(string: covers["medium"] as! NSString as String)
                        if let data = NSData(contentsOfURL: url!) {
                            portada = UIImage(data: data)!
                        }

                    }
                    print("LIBRO:" + titulo)
                    let libro : Libro = Libro(nombre : titulo,autores: autores, portada: portada)
                    mvc.libros.append(libro)
                    for x in mvc.libros {
                        print (x.nombre)
                    }
                    mvc.actualiza(libro)

                }
            }
        } catch _ {
        }
    }
}

mvc.actualiza 函数执行以下操作:

func actualiza (libro:Libro) {
    let context = self.fetchedResultsController.managedObjectContext
    let entity = self.fetchedResultsController.fetchRequest.entity!
    let newManagedObject = NSEntityDescription.insertNewObjectForEntityForName(entity.name!, inManagedObjectContext: context)

    // If appropriate, configure the new managed object.
    // Normally you should use accessor methods, but using KVC here avoids the need to add a custom class to the template.
    newManagedObject.setValue(libro as? AnyObject, forKey: "timeStamp")

    // Save the context.
    do {
        try context.save()
    } catch {
        // Replace this implementation with code to handle the error appropriately.
        // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
        //print("Unresolved error \(error), \(error.userInfo)")
        abort()
    }
}

执行第一行时,此处崩溃:

let entity = NSEntityDescription.entityForName("Event", inManagedObjectContext: self.managedObjectContext!)

我收到以下错误消息:

fatal error: unexpectedly found nil while unwrapping an Optional value

从一个 View Controller 到另一个 View Controller 的转换中我缺少什么?

最佳答案

看起来self.managementObjectContext尚未初始化。您可以尝试将其放在故障线路之前进行检查:

print("managedObjectContext: \(self.managedObjectContext)")

关于swift - NSFetchRequest - 实体 - 解包可选值时意外发现 nil,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35157446/

相关文章:

Swift 协议(protocol)在基类中存在时允许未实现的函数

ios - 如何使用键盘 "Go"像 Swift 2 中的 UIButton 一样提交 UITextFields

ios - 如何使用 mapView 和 CLLocationManager 在 iOS Swift 中绘制两个位置之间的方向

swift - 代码 : "Module not found" for Toast_Swift in only one view controller

objective-c - AFNetworking pod install 使用未解析的标识符方法

ios - 从 UIDocumentBrowserViewController 获取 UIActivityViewController 的 sourceRect

ios - 如何在 View Controller 之间同步索引

swift - 如何读取套接字中的所有行(快速)

ios - ENABLE_BITCODE 问题。 Xcode 7 归档问题

ios - Size classes 在 Swift 2.0 中无法正常工作