ios - fatal error : unexpectedly found nil while unwrapping an Optional value - Core Data (Swift)

标签 ios swift core-data fatal-error

当我实现获取的托管对象核心数据代码时,出现此包装错误。当前收到 fatal error :在解包可选值时意外发现 nil。我做错了什么?

View Controller :

 func saveRun() {
            // 1
            let savedRun = NSEntityDescription.insertNewObject(forEntityName: "Run", into: managedObjectContext!) as! Run
            savedRun.distance = NSNumber(value: distance)
            savedRun.duration = (NSNumber(value: seconds))
            savedRun.timestamp = NSDate() as Date



            // 2
            var savedLocations = [Location]()
            for location in locations {
                let savedLocation = NSEntityDescription.insertNewObject(forEntityName: "Location",
                                                                        into: managedObjectContext!) as! Location
                savedLocation.timestamp = (location.timestamp as NSDate) as Date
                savedLocation.latitude = NSNumber(value: location.coordinate.latitude)
                savedLocation.longitude = NSNumber(value: location.coordinate.longitude)
                savedLocations.append(savedLocation)
            }
            savedRun.locations = NSOrderedSet(array: savedLocations)
            run = savedRun

            do{
                try managedObjectContext!.save()
            }catch{
                print("Could not save the run!")
            }
        }

应用程序委托(delegate):

  // MARK: - Core Data stack

    lazy var applicationDocumentsDirectory: URL = {
        // The directory the application uses to store the Core Data store file. This code uses a directory named "com.zedenem.MarathonRun" in the application's documents Application Support directory.
        let urls = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
        return urls.last!
    }()

    lazy var managedObjectModel: NSManagedObjectModel = {
        // The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model.
        let modelURL = Bundle.main.url(forResource: "MarathonRun", withExtension: "momd")!
        return NSManagedObjectModel(contentsOf: modelURL)!
    }()

    lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator? = {
        // The persistent store coordinator for the application. This implementation creates and return a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail.
        // Create the coordinator and store
        var coordinator: NSPersistentStoreCoordinator? = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
        let url = self.applicationDocumentsDirectory.appendingPathComponent("MarathonRun")
        var error: NSError? = nil
        var failureReason = "There was an error creating or loading the application's saved data."
        do {
            try coordinator!.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: url, options: nil)
        }catch let error as NSError {
            coordinator = nil
            // Report any error we got.
            var dict = [AnyHashable: Any]()
            dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data"
            dict[NSLocalizedFailureReasonErrorKey] = failureReason
            dict[NSUnderlyingErrorKey] = error

            print("Error: \(error.domain)")
            abort()
        }
        return coordinator
    }()

    lazy var managedObjectContext: NSManagedObjectContext? = {
        // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail.
        let coordinator = self.persistentStoreCoordinator
        if coordinator == nil {
            return nil
        }
        var managedObjectContext = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType)//NSManagedObjectContext()
        managedObjectContext.persistentStoreCoordinator = coordinator
        return managedObjectContext
    }()

    // MARK: - Core Data Saving support

    func saveContext () {
        if let moc = self.managedObjectContext {
            if moc.hasChanges{
                do{
                    try moc.save()
                }catch let error as NSError{
                    print("Error: \(error.domain)")
                }
            }
        }

请查看截图enter image description here enter image description here

最佳答案

您的 managedObjectContext 对象是 nil 并且您已用 ! 强制将其包装,这将导致崩溃。

因此,在执行此操作之前:

let savedRun = NSEntityDescription.insertNewObject(forEntityName: "Run", into: managedObjectContext!) as! Run

确保您有一个 managementObjectContext 值:

if let managedObjectContext = [get the managedObjectContext object here] {
     // If you succeed with getting the managedObjectContext, then you can use it without the ! in here
     let savedRun = NSEntityDescription.insertNewObject(forEntityName: "Run", into: managedObjectContext) as! Run
}

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

相关文章:

iphone - 本地化动态 NSString

ios - UICollectionView 数据未正确显示

ios - UIStackView 在 Swift 中没有成员委托(delegate)错误

ios - CNContactViewController setEditing true before appear

ios - Swift 改变 Coredata 的值,而不是创建新的

ios - objective-c : Send coredata objects by imessage & eMail

ios - 在圆形路径上移动 View

ios - 根据部分更改选定的单元格图像

ios - UITableView 设置不同的图片

iphone - Float on core-data 的问题