В настоящее время я работаю с Swift 2.0 и создал новое приложение «Master-Detail» в X-Code. Мне нужно, когда пользователь нажимает на BarButtomItem, появляется новый вид, запрашивающий текстовое поле, которое будет выполнять поиск в Интернете. код, чтобы открыть ViewController выглядит следующим образом:NSFetchRequest - сущность - неожиданно найден nil во время разворачивания необязательного значения
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. Чтобы сделать это, Im вызывая функцию обновления с точки зрения контроллера:
Функция в 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
Что мне не хватает для перехода с одного контроллера на другой?
в случае, если он не инициализирован, как я могу его инициализировать? @ emrys57 – user1084509
не инициализирован. Дело в том, что когда он загружается в первый раз, он инициализируется ... но когда я открываю другое представление и затем хочу вернуться к основному, переменная managedObjectContext больше не инициализируется. Как я мог его инициализировать? @ emrys57 – user1084509
Я не вижу, как ответить на это, не зная больше о контроллерах. Возможно, вы должны задать новый вопрос, показывающий другой код. – emrys57