Quote:
Originally Posted by hstaniloff
Hmmm... The reason I am asking is that when I run the app in the simulator, the database file does not exist yet in the documents folder. So as per the template, a blank db is copied from the applications bundle to the documents folder.
This blank db had to be created somehow. And that's my question: How do you initially create a blank database based on your xcdatamodel schema?
|
I assume you've figured this out by now, but if you use the Xcode templates to build a Navigation- or Window-based app, Xcode will create an empty DB for you using the name "<yourappname>.sqlite" if it doesn't already exist. The template doesn't copy anything from your app bundle, unless...
...you want to. If you
want to copy over a prefilled database, you can do that in the persistentStoreCoordinator getter in your appDelegate file. Assuming you've created a fully fleshed out Core Data app that has data in it and have run it on the iPhone simulator:
- Close the app
- Look for your app in one of the folders in ~/Library/Application\ Support/iPhoneSimulator/User/Applications
- You'll see a lot of folders with UUIDs for names. If your app was the last one run, you can sort the folders by Date Modified to find yours.
- Once you find the right folder, look in the Documents folder and you'll see your .sqlite database. Drag it into your project anywhere (I stick mine in the Resources group normally.)
- Now in the appDelegate file, replace the persistentStoreCoordinator getter with the following:
Code:
- (NSPersistentStoreCoordinator *) persistentStoreCoordinator
{
if (persistentStoreCoordinator != nil)
{
return persistentStoreCoordinator;
}
NSString *storePath = [[self applicationDocumentsDirectory] stringByAppendingPathComponent:ksDatabaseFilename];
#if defined(USE_DEMO_DATABASE)
// if we're testing, use a pre-built sample database.
NSFileManager *fileManager = [NSFileManager defaultManager];
// If the expected store doesn't exist, copy the default store.
if ( ! [fileManager fileExistsAtPath:storePath])
{
NSString *defaultStorePath = [[NSBundle mainBundle] pathForResource:@"Travellers" ofType:@"sqlite"];
if ( defaultStorePath )
{
[fileManager copyItemAtPath:defaultStorePath toPath:storePath error:NULL];
}
}
#endif
NSURL *storeUrl = [NSURL fileURLWithPath:storePath];
NSError *error;
persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel: [self managedObjectModel]];
if ( ! [persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeUrl options:nil error:&error])
{
// Handle error
}
return persistentStoreCoordinator;
}
Obviously, #define USE_DEMO_DATABASE somewhere to use the copy function.
Now your app has a pre-cooked Core Data object context.
--r