I've been strungling with Core Data. I've looked at the examples and documentation but they all seem to copy an existing SQLite DB into the working directory. I've defined my data model and just want Core Data to create a SQLite DB. I then will populate the db im my开发者_运维知识库 app.
Can anyone show me how?
I've looked at the examples and documentation but they all seem to copy an existing SQLite DB into the working directory.
Which book did you read? I guess you somehow found only strange sets of examples... anyhow.
It's very easy.
- Create an
NSPersistentStoreCoordinator
and tie it to a file name byaddPersistentStoreWithType:configuration:URL:options:error:
. (The file doesn't have to exist at this stage. Maybe this part confused you. You need to specify the file name to which the data is later saved.) - Get an
NSManagedObjectContext
associated to it.
At this stage, the set up of Core Data is ready. Next,
- Create an
NSEntityDescription
for your entity. - Create the object by
[[NSManagedObject alloc] initWithEntity:entity insertIntoManagedObjectContext:moc]
At this stage, one object is inserted to the context, but is not saved to the disk. When you're done, you do
[moc save:&error];
This will create the SQL file on the disk. You should examine the examples provided by Apple itself, already linked by other posters here. Read also the tutorials provided by Apple itself, like this. They are quite good.
Also, buy Marcus Zarra's Core Data Book, which is very good and helped me a lot.
You do something like this to set up the persistent store coordinator & create the database (code taken from the Apple "Recipes" sample application)
NSString *storePath = [[self applicationDocumentsDirectory]
stringByAppendingPathComponent:@"MyDB.sqlite"];
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]) {
NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
}
The SQLite is created automatically, but only if the database does not already exists
Remove the app from the iPhone / Simulator to clean it up
The easiest way is to use the Xcode templates that include Core Data to generate a project already configured. Look at the persistentStoreCoordinator
method to learn how they define the location and type of the persistent store. The Core Data Programming Guide also has instructions. The default is XML, but you can easily change this to NSSQLiteStoreType
. Your program will generate a new database the first time it runs.
精彩评论