wiruzx wiruzx - 18 days ago 10
iOS Question

How to import SQLite table into Core Data(SQLite too)

I have a large XML. If I write it to the database by one record, is about 2 minutes. This XML static, it is never updated. So it may be useful to create SQLite database and import one table in Core Data? How can I do this?

I saw this tutorial (Core Data on iOS 5 Tutorial: How To Preload and Import Existing Data) and it does not say how to import table

Answer

importing from sqlite is rather easy but not documented enough IMHO

  1. open you app and set up the core data stack
  2. open the legacy sql database from which you want to import stuff
  3. get the data to import and loop over all the rows.
  4. for each row, create a new NSManagedObject and insert it into the managedObject context you are using 4a. set it up with the values.

using FMDB it would be like:

NSManagedObjectContext *mom = ... ; //your mom


FMDatabase *db = [FMDatabase databaseWithPath:libraryDatabase];
if(![db open]) {
    ddprintf(@"Failed to open database at %@", libraryDatabase);
    return;
}

if(![db beginTransaction]) {
    ddprintf(@"Failed to start Transaction to update database: %d, %@", db.lastErrorCode, db.lastErrorMessage);
    [db close];
    return;
}

id sql = @"SELECT modelId,imagePath,fileVolumeUuid FROM RKMaster";
FMResultSet *resultSet = [db executeQuery:sql];
while ([resultSet next]) {
    //get row values
    NSString *modelId = [row stringForColumn:@"modelId"];
    NSString *orgFilename = [row stringForColumn:@"imagePath"];

    //new MOC
    MyEntity *entity = [mom insertNewObjectForEntity:@"myEntity"];
    entity.modelId = modelId;
    entity.orgFilename = orgFilename;
}

if(![db commit]) {
    ddprintf(@"Failed to commit database transaction: %d,%@", [db lastErrorCode], [db lastErrorMessage]);
}

if(![db close]) {
    ddprintf(@"Failed to propertly close database at %@", libraryDatabase);
}