Reputation: 87
I'm using Swift 2.2 iOS 9.3.1 and 9.3.2 (beta) iPhone 5s and 6s.
When running the simulator with iPhone 5s and 9.3, Core Data retains the database after a reboot. But not when run on the physical devices.
I've made a very simple to-do app to learn more Swift and now Core Data. I've followed some tutorials as https://www.raywenderlich.com/115695/getting-started-with-core-data-tutorial and Apples Core Data Programming guide.
This SO Xcode Swift application deployed to iphone losses CoreData after iPhone reboot have what looks like the same issue, but little activity. Hoping that bringing more info to the table would help with my issue.
I do save the MOC when the app enters background and when it terminates. I'm calling this function in my DataController and observing that it prints the expected text.
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()
}
}
}
I am saving to the Documents directory as suggested by others.
...
let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
...
I've tried googling this for several hours but I can't wrap my head around why this should happen. But my googling skills just ain't strong enough or I'm just overlooking the obvious.
Upvotes: 0
Views: 136
Reputation: 162
I use this function and after iphone reboot I still have my datas.
// 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)")
}
}
Upvotes: 1