我創建了一個應用程序來保存學生的細節,使用NSPersistanceContainer,而我從json獲取數據並保存到數據庫,當時我「M越來越擷取結果計數> 0,如果我重新抓取結果計數返回0viewContext沒有被保存在數據庫(app.sqlite)SWIFT
lazy var persistentContainer: NSPersistentContainer = {
let container = NSPersistentContainer(name: "Students_dev")
let storeURL = try! FileManager
.default
.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
.appendingPathComponent("Students_dev.sqlite")
print("URL :",storeURL)
let storeDescription = NSPersistentStoreDescription(url: storeURL)
storeDescription.shouldMigrateStoreAutomatically = true
storeDescription.shouldMigrateStoreAutomatically = true
container.viewContext.automaticallyMergesChangesFromParent = true
container.persistentStoreDescriptions = [storeDescription]
container.loadPersistentStores(completionHandler: { (storeDescription, error) in
if let error = error as NSError? {
fatalError("Unresolved error \(error), \(error.userInfo)")
}
})
return container
}()
// MARK: - Core Data Saving support
func saveContext (context: NSManagedObjectContext) {
persistentContainer.performBackgroundTask({ (context) in
if context.hasChanges {
do {
try context.save()
} catch {
let nserror = error as NSError
fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
}
}
})
}
上下文不爲空而我保存到數據庫,當我檢查sqlite的文件表是應用程序空。沒有得到我方遺漏的東西。
現在,警告已經走了,但是當我檢查sqllite文件中的數據顯示我空。 – Joe
您是否嘗試在saveContext方法上設置斷點並檢查context.hasChanges是否爲true?我只能猜測你可能沒有保存創建新對象的上下文嗎? – kharrison
context.hasChanges返回true – Joe