开发者

How to import a pre-existing sqlite file into Core Data?

I need to import a .sqlite file into Core Data, I searched on the internet and开发者_C百科 found:

Core Data Tutorial: How To Preload/Import Existing Data

It is creating a Python script to populate this database by reading in the contents of our old database, and creating the appropriate rows in the new database. But my sqlite database is too large in term of number of tables and columns, this may cost me a considerable amount of time.

I also found this:

Using a Pre-Populated SQLite Database with Core Data on iPhone OS 3.0

But I don't quite understand it, it looks like it's copying old database to a new one, then how does it add Z_ suffix to all the table and column names? Also, it asks me to create entities and attributes, is there anyway this can be done automatically(from sqlite dabase file)?

Thanks!


This answers here might be useful (mine is one of them)

Pre-populate Core Data

 /**
 Returns the path to the application's Documents directory.
*/
      - (NSString *)applicationDocumentsDirectory {
          return [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,  NSUserDomainMask, YES) lastObject];
      }

sample code


// Returns the persistent store coordinator for the application.
// If the coordinator doesn't already exist, it is created and the application's store added to it.
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator
{
    if (_persistentStoreCoordinator != nil)
    {
        return _persistentStoreCoordinator;
    }

    NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"yourSqlite.sqlite"];

    NSString *sourcePath = [[NSBundle mainBundle] pathForResource:@"yourSqlite.sqlite" ofType:nil];

    NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    NSError *error = nil;

    if  (![[NSFileManager defaultManager] fileExistsAtPath:[documentsDirectory stringByAppendingPathComponent:@"yourSqlite.sqlite"] ]) {

        if([[NSFileManager defaultManager] copyItemAtPath:sourcePath toPath:[documentsDirectory stringByAppendingPathComponent:@"yourSqlite.sqlite"] error:&error]){
            NSLog(@"Default file successfully copied over.");
        } else {
            NSLog(@"Error description-%@ \n", [error localizedDescription]);
            NSLog(@"Error reason-%@", [error localizedFailureReason]);
        }
    }

    _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;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜