我正在使用Swift 2.2 iOS 9.3.1和9.3.2(beta)iPhone 5s和6s。
使用iPhone 5s和9.3运行模拟器时,Core Data会在重新启动后保留数据库。但不是在物理设备上运行时。
我做了一个非常简单的待办事项应用程序,以了解更多Swift和现在的核心数据。我已经按照一些教程了 https://www.raywenderlich.com/115695/getting-started-with-core-data-tutorial和Apples 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搜索了几个小时,但我无法理解为什么会发生这种情况。但我的谷歌搜索技巧还不够强大,或者我只是忽略了显而易见的事情。
答案 0 :(得分: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)")
}
}