当我实现获取的托管对象核心数据代码时,我收到此包装错误。目前正在获取fatal error: unexpectedly found nil while unwrapping an Optional value
。我做错了什么?
ViewController:
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!")
}
}
App代表:
// 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)")
}
}
}
答案 0 :(得分:1)
您的managedObjectContext
对象为nil
,并且您已强制将其与!
包裹起来,这将导致崩溃。
所以在你这样做之前:
let savedRun = NSEntityDescription.insertNewObject(forEntityName: "Run", into: managedObjectContext!) as! Run
确保您拥有managedObjectContext
的价值:
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
}
答案 1 :(得分:0)
通过阅读评论进行一些调查后,崩溃的原因很可能是您只是声明托管对象上下文
var managedObjectContext: NSManagedObjectContext?
但在视图控制器中没有初始化。所以它仍然是nil
并导致崩溃。
从AppDelegate获取上下文的一种合适方法是一个惰性实例化属性
lazy var managedObjectContext : NSManagedObjectContext = {
let appDelegate = UIApplication.shared.delegate as! AppDelegate
return appDelegate.managedObjectContext
}()
现在你的saveRun()
方法应该有效。
顺便说一下:不要将AppDelegate中的persistentStoreCoordinator
和managedObjectContext
初始化为可选项。那是胡说八道。该应用程序是不可行的,如果无法创建协调器,它将终止。
lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = {
// Create the coordinator and store
let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
let url = self.applicationDocumentsDirectory.appendingPathComponent("MarathonRun")
do {
try coordinator.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: url, options: nil)
} catch let error as NSError {
// Report any error we got.
var dict = [AnyHashable: Any]()
dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data"
dict[NSLocalizedFailureReasonErrorKey] = "There was an error creating or loading the application's saved data."
dict[NSUnderlyingErrorKey] = error
print("Error: ", error)
abort()
}
return coordinator
}()
lazy var managedObjectContext: NSManagedObjectContext = {
let coordinator = self.persistentStoreCoordinator
var managedObjectContext = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType)//NSManagedObjectContext()
managedObjectContext.persistentStoreCoordinator = coordinator
return managedObjectContext
}()
另一个繁琐的代码是将Double
转换为NSNumber
的舞蹈,反之亦然。将latitude
子类中的longitude
和NSManagedObject
声明为Double
是完全合法的。同样的事情是date
属性。将它们声明为Date
以避免大量类型转换。
答案 2 :(得分:-1)
你可以使用if,所以你的应用程序不会崩溃。
if let savedRun = NSEntityDescription.insertNewObject(forEntityName: "Run", into: managedObjectContext!) as! Run {
}
但是对于永久性修复,请重新检查Run Entity类。