Learn how to use Core Data migrations in Swift to keep your data models up-to-date!
This is a companion discussion topic for the original entry at https://www.raywenderlich.com/1547-core-data-migrations-tutorial-lightweight-migrations
Learn how to use Core Data migrations in Swift to keep your data models up-to-date!
Hi,
How to merge data from a bundle database to an already existing store.
-anoop
If you have a sample database in your app bundle, you can simply use NSFileManager to copy (not move) the sample database to a location where you can modify your copy. Your code will look something like this:
let appBundle = NSBundle.mainBundle()
let databaseInAppBundlePath = appBundle.pathForResource("mydatabase", ofType: "sqlite")
let fileManager = NSFileManager()
let destinationPath = fileManager.createDirectoryAtPath(databaseInAppBundlePath.stringByDeletingLastPathComponent, withIntermediateDirectories: true, attributes: nil)
do {
try fileManager.copyItemAtPath(databaseInAppBundlePath, toPath: destinationPath)
}
catch let error as NSError {
print("Unable to copy template database: \(error)")
}
Final project doesn’t work.
Missing self.options assignment
self.store = try coordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil,
URL: self.storeURL,
options: nil)
You say if we are using Core Data as an offline cache, “you can simply delete and rebuild the data store”. I can’t find an example of this anywhere. Can you tell me how to do this please? Thanks in advance.
It’s a rather simple idea that applies to any cache. Typically, anytime you want to expire data from a cache, you simply remove the backing file. The same is true if you want to use Core Data this way. You can simply delete all the Core Data store files using NSFileManager. If you’re using SQLite as your persistent store type, don’t forget to delete your Write Ahead Log and your Shared Memory files as well. Then, the next time you launch your Core Data stack, the store will be reinitialized with an empty, valid database. So, when using Core Data as an offline cache, you just need to delete all the data store files and reset your Core Data stack (typically by reallocing your current stack).
casademora, do you know of any sample code for doing that?