How do I do initial data configuration setup with CoreData?
I've got an app 开发者_StackOverflow中文版using CoreData as a data storage mechanism and the app needs some initial data to be configured. Are there any recommendations / what/how are you doing in order to set up the initial data?
Currently I am doing it in the following way (when the app starts for the 1st time):
SomeEntity *newEntity=[NSEntityDescription insertNewObjectForEntityForName:@"SomeEntity" inManagedObjectContext:context];
[newEntity setCode:@"a-code"];
[newEntity setName:@"a-name"];
...
[context save:nil];
I do not like this approach for 2 reasons:
1) it's so boring and error-prone if you need more than 10 entity instances for more than one entity type 2) it may take up some time for the initial start-upIn previous apps using SQLite I just linked my initial SQLite database into the app and, if needed to modify any data, moved the database to the Documents directory. Is there any similar approach for CoreData?
That's exactly what you'd do with Core Data, too. Use your app to create the data the way you want, and then download the data from the device. You'll find a SQLite file in the Documents directory (which is the default location). Add the SQLite file to your project as a resource. It'll get copied along with your app.
Then, all you need to do is write some code to determine if a file already exists in the Documents directory on startup. If not, you can copy the file from your application's bundle to the Documents directory and Core Data will open that. You just want to make sure to do this before the NSPersistentStoreCoordinator
is set up.
精彩评论