2016-05-11 65 views
0

我使用的是Swift 2.2 iOS 9.3.1和9.3.2(beta)iPhone 5s和6s。核心數據在iPhone重啓後不會保留數據庫

當用iPhone 5s和9.3運行模擬器時,核心數據在重新引導後保留數據庫。但在物理設備上運行時不行。

我已經做了一個非常簡單的應用程序來了解更多Swift和現在的核心數據。我遵循 https://www.raywenderlich.com/115695/getting-started-with-core-data-tutorialApples Core Data Programming guide的一些教程。

這個SO Xcode Swift application deployed to iphone losses CoreData after iPhone reboot有看起來像是一樣的問題,但活動很少。希望將更多的信息帶到桌面將有助於解決我的問題。

當應用程序進入後臺並終止時,我會保存MOC。我在我的DataController中調用這個函數,並觀察它打印預期的文本。

func saveContext() { 
     if managedObjectContext.hasChanges { 
      do { 
       try managedObjectContext.save() 
       print("DataController saveContext") 
      } catch { 
       let nserror = error as NSError 
       NSLog("Unresolved error \(nserror), \(nserror.userInfo)") 
       abort() 
      } 
     } 
    } 

我正按其他人的建議保存到Documents目錄。

... 
let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask) 
... 

我試過用google搜索了幾個小時,但是我無法用頭圍住爲什麼會發生這種情況。但是我的谷歌搜索技能還不夠強,或者我只是忽視了這些顯而易見的問題。

回答

1

我使用這個功能,並在iPhone重新啓動後,我仍然有我的數據。

// Save data to CoreData 
func saveLocalUserProfile(variables, ....) { 
    // ---------------------------------------------- 
    // Create the core data object 
    let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate 
    let managedContext = appDelegate.managedObjectContext 
    let entity = NSEntityDescription.entityForName("YourTable", inManagedObjectContext:managedContext) 
    let userProfile = NSManagedObject(entity: entity!, insertIntoManagedObjectContext: managedContext) 
    // ---------------------------------------------- 
    // Set datas 
    userProfile.setValue(variable, forKey: "varaible") 
    .... 

    // ----------------------------------------------- 
    // Save data into Core Data 
    do { 
     try managedContext.save() 
     print("Save ok") 
    } catch let error as NSError { 
     print("Could not save \(error), \(error.userInfo)") 
    } 
} 
+0

我看不出我做得非常不同。猜猜我會寫一個更簡單的應用程序,看看這個問題是否存在。我也會嘗試使用較早版本的iOS找到iPhone。謝謝。 – oey