NSFetchRequest - 实体 - 在展开Optional值时意外地找到了nil

时间:2016-02-02 15:28:28

标签: swift swift2 xcode7 nsfetchrequest

我目前正在使用Swift 2.0并在X-Code中创建了一个新的“Master-Detail Application”。我需要在用户单击BarButtomItem时,会出现一个新视图,请求在Internet上进行搜索的文本字段。 打开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中。为此,我从视图控制器调用更新函数:

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!)

我收到以下错误消息:

  

致命错误:在解包可选值时意外发现nil

在从一个视图控制器转换到另一个视图控制器时,我缺少什么?

1 个答案:

答案 0 :(得分:0)

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

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