2017-10-28 309 views
0

我創建了一個應用程序來保存學生的細節,使用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的文件表是應用程序空。沒有得到我方遺漏的東西。

沒有數據插入到了SQL文件 screenshot of sql log

回答

0

的問題是在saveContext功能,上下文是沒有得到保存到核心數據「persistentContainer.performBackgroundTask」,當我刪除它,它工作正常。

代碼

func saveContext (context: NSManagedObjectContext) { 

    if context.hasChanges { 
     do { 
      try context.save() 
     } catch { 
      let nserror = error as NSError 
      fatalError("Unresolved error \(nserror), \(nserror.userInfo)") 
     } 
    } 
} 
0

我覺得CoreData警告的原因是這行代碼:

container.viewContext.automaticallyMergesChangesFromParent = true 

之前,您正在訪問的viewContext商店被加載。嘗試移動負載持久性存儲完成塊內該行:

container.loadPersistentStores(completionHandler: { (storeDescription, error) in 
    if let error = error as NSError? { 
     fatalError("Unresolved error \(error), \(error.userInfo)") 
    } 
    container.viewContext.automaticallyMergesChangesFromParent = true 
}) 
+0

現在,警告已經走了,但是當我檢查sqllite文件中的數據顯示我空。 – Joe

+0

您是否嘗試在saveContext方法上設置斷點並檢查context.hasChanges是否爲true?我只能猜測你可能沒有保存創建新對象的上下文嗎? – kharrison

+0

context.hasChanges返回true – Joe

相關問題