2

I have to preload data into my core data to have always my entities full of data, since the first time someone start the application. I have a database in csv and other sqlite. which is the best? and How should I do it? I mean, I guess I should have my database always in a folder of my app and the first time I launch the app I will fill data into database. isn't it? or I am wrong? if this is the good way? How I do it?

4

2 回答 2

1

I would recommend an already mapped CoreData store. Whether it have been previously mapped by your app or by an editor such as Core Data Editor.

In the app delegate you can preload the data. In - (NSPersistentStoreCoordinator *)persistentStoreCoordinator.

You can remove the current store:

NSError *error = nil;
NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"CoreDataStore.sqlite"];
[[NSFileManager defaultManager] removeItemAtPath:storeURL.path error:&error];

And you can move the preloaded store into place if there isn't already a store:

NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"CoreDataStore.sqlite"];
if (![[NSFileManager defaultManager] fileExistsAtPath:[storeURL path]]) {
    NSURL *preloadURL = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"PreloadData" ofType:@"sqlite"]];
    NSError* err = nil;

    if (![[NSFileManager defaultManager] copyItemAtURL:preloadURL toURL:storeURL error:&err]) {
        NSLog(@"Oops, couldn't copy preloaded data");
    }
}
于 2013-10-17T23:54:27.907 回答
0

这取决于你拥有什么样的数据。真正重要的唯一问题是哪一个更适合您的数据,因为任何一个都可以很好地编写代码来导入数据。

如果您的数据包含具有关系的多种类型的实体,SQLite 将比 CSV 更好地映射它。如果没有,请使用您个人认为最方便处理的任何内容。

于 2013-10-18T00:19:26.593 回答