I want to introduce the ability for the my core-data app to download a NEW sqlite file and update its stored data. Note the data model is not changing.
At first I am not worrying about user changes to the stored data, and simply want to overwrite it.
- I am finding the only way the stored data is updating is to change the name of the sqlite file.. ?
- Is there a standatd way to merge, via core-data, 2 sqlite files? Thus keeping user modified data.
- Can an update (downloaded sqlite file) be a su开发者_开发百科bset of the shipped core data sqlite? Note the sqlite contains binary information.
I think this SO question falls short in answering these things.
Thanks for any guideance!
If you want to Update any data base file without modifying existing data base then you have to implement like this
- (void)applicationDidFinishLaunching:(UIApplication *)application {
[self createEditableCopyOfDatabaseIfNeeded];
}
- (void)createEditableCopyOfDatabaseIfNeeded {
// First, test for existence - we don't want to wipe out a user's DB
NSFileManager *fileManager = [NSFileManager defaultManager];
NSString *documentDirectory = [self applicationDocumentsDirectory];
NSString *writableDBPath = [documentDirectory stringByAppendingPathComponent:@"DataBaseName.sqlite"];
BOOL dbexits = [fileManager fileExistsAtPath:writableDBPath];
if (!dbexits) {
// The writable database does not exist, so copy the default to the appropriate location.
NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"DataBaseName.sqlite"];
NSError *error;
BOOL success = [fileManager copyItemAtPath:defaultDBPath toPath:writableDBPath error:&error];
if (!success) {
NSAssert1(0, @"Failed to create writable database file with message '%@'.", [error localizedDescription]);
}
}
}
I know this is an old question, but after tackling this myself I just wanted to add the following points:
- The default sqlite file for a core data store, yourProjectName.sqlite, seems to be protected. Overwriting it doesn't work. You will need to do what raaz suggested above and create a copy.
- After creating the copy you can overwrite the file easily. However, some suggestions in other answers show that the best way to overwrite the core data sqlite file is to delete it first. This doesn't work on the device! It throws an error saying it couldn't remove the file. It does work in the simulator, but not on the device (tested on a 3G on 4.2)
- So the best way is to just overwrite the file rather than deleting it and creating a new one.
- And of course be sure to remove the store from the persistent store coordinator first!
My 2c, hope it helps someone.
精彩评论