Unable to unpack optionally. When using CoreData in Swift

So, the problem actually arises after the context of the code code bit: NSManagedObjectContext = appDel.managedObjectContext is launched. I commented on this to confirm that it was that line, and that was, please note that this is my first iOS programming experience, so please try to be as specific as possible in your answer, thanks :)

import UIKit
import CoreData
class SecondViewController: UIViewController, UITextFieldDelegate {

@IBOutlet var txtName : UITextField
@IBOutlet var txtDesc : UITextField
override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
}

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

override func touchesBegan(touches: NSSet!, withEvent event: UIEvent!)  {
    self.view.endEditing(true)
}

@IBAction func hitAdd(sender : UIButton) {
    glTask.newTask(txtName.text, desc: txtDesc.text)
    txtName.text = ""
    txtDesc.text = ""
    self.view.endEditing(true)
    self.tabBarController.selectedIndex = 0
    var appDel: AppDelegate = (UIApplication.sharedApplication().delegate as AppDelegate)

Right here v

    var context: NSManagedObjectContext = appDel.managedObjectContext

This causes the application to crash after clicking ^

Code Error Message : Fatal Error Cant unwrap Optional. Non-profit

    var newTask = NSEntityDescription.insertNewObjectForEntityForName("Tasks", inManagedObjectContext: context) as NSManagedObject
    newTask.setValue("test task", forKey: "myTask")
    newTask.setValue("test Description", forKey: "myDesc")
    context.save(nil)
    //println(newTask)
    println("Task was saved.")

}

// UITextField Delegate
func textFieldShouldReturn(textField: UITextField!) -> Bool {

    textField.resignFirstResponder()
    return true
}

}

+4
source share
2

Swift, managedObjectContext :

var managedObjectContext: NSManagedObjectContext {
    if !_managedObjectContext {
        let coordinator = self.persistentStoreCoordinator
        if coordinator != nil {
            _managedObjectContext = NSManagedObjectContext()
            _managedObjectContext!.persistentStoreCoordinator = coordinator
        }
    }
    return _managedObjectContext!
}
var _managedObjectContext: NSManagedObjectContext? = nil

, .

, , :

  _managedObjectContext = NSManagedObjectContext()
  _managedObjectContext!.persistentStoreCoordinator = coordinator

NSManagedObjectContext() a nil, _managedObjectContext , , return _managedObjectContext!

, , , , , nil.

Edit: var persistentStoreCoordinator: NSPersistentStoreCoordinator

( ), .

+4

, OP - , , , , AppDelegate, : let modelURL = NSBundle.mainBundle().URLForResource("CoreData", withExtension: "momd") "CoreData" "", .

0

Source: https://habr.com/ru/post/1543889/


All Articles