如何在Swift中打印出Core Data保存错误?
至于我有这两行:
var error: AutoreleasingUnsafePointer<NSError?> = nil
let success = managedObjectContext.save(error)
答案 0 :(得分:8)
func saveContext () {
if managedObjectContext.hasChanges {
do {
try managedObjectContext.save()
} catch let nserror as NSError {
// 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 \(nserror), \(nserror.userInfo)")
abort()
}
}
}
答案 1 :(得分:3)
您必须将指针传递给可选的NSError
对象。
例如,如果您创建iOS应用并选择,则这是来自Xcode的模板代码
&#34;使用核心数据&#34;复选框:
func saveContext () {
if let moc = self.managedObjectContext {
var error: NSError? = nil
if moc.hasChanges && !moc.save(&error) {
// Replace this implementation with code to handle the error appropriately.
// ...
NSLog("Unresolved error \(error), \(error!.userInfo)")
abort()
}
}
}