2

我有一个很大的 XML。如果我通过一条记录将其写入数据库,大约需要 2 分钟。这个 XML 是静态的,它永远不会更新。那么在 Core Data 中创建 SQLite 数据库并导入一张表可能有用吗?我怎样才能做到这一点?

我看到了本教程(iOS 5 上的核心数据教程:如何预加载和导入现有数据)并没有说明如何导入表

4

1 回答 1

4

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);
}
于 2013-04-29T08:27:55.730 回答