To pre-populate CoreData in my app upon first launch, I have included a PreModel.sqlite file that was previously created by the app from data that it downloaded from a web service, which includes images.
To populate the model, I do this:
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator
{
if (_persistentStoreCoordinator != nil) {
return _persistentStoreCoordinator;
}
NSLog(@"creating new store");
NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"PreModel.sqlite"];
if(![[NSFileManager defaultManager] fileExistsAtPath:[storeURL path]]) {
NSString *sqlitePath = [[NSBundle mainBundle] pathForResource:@"PreModel" ofType:@"sqlite"];
if (sqlitePath) {
NSError *error = nil;
[[NSFileManager defaultManager] copyItemAtPath:sqlitePath toPath:[storeURL path] error:&error];
if (error) {
NSLog(@"Error copying sqlite database: %@", [error localizedDescription]);
}
}
}
NSError *error = nil;
_persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error]) {
NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
abort();
}
return _persistentStoreCoordinator;
}
It seems to work. But I have 2 questions:
- If the sqlite file is just a database file and does not actually contain any images, how is the app finding and loading the images on first launch?
- Even on subsequent runs of the app I see “creating new store” logged every time. Why is
_persistentStoreCoordinatoralways nil? I am clearly setting it in the code.
“Creating new store” is expected to get logged every time the app is launched in this instance. Even though the SQLite file is persistent on disk, you can’t expect data structures in your code to stick around when your app is terminated – you need to create a new persistent store object for your program every time it launches.
Think of it like assigning
NSInteger x = 10, then expecting to be able to quit and relaunch your program while maintaining thatxhas the value 10. That’s not how programs work – you’d need to reassignx = 10before you can expect to readxand get 10 back. The variable_persistentStoreCoordinatorworks the same way here.