SQLite データベースからのコア データの「アップサート」
-
22-09-2019 - |
質問
私は現在、さまざまなデータを変更および保持する機能を必要とするアプリを作成しています。この目的のために Core Data を使用することにしました。ユーザーが初めてアプリケーションを開いたときに、sqlite データベースから大量のデータをインポートする必要があります。このデータは多対多の関係で構成されています。
このすべてのデータをコード データ ストアに挿入する最良の方法を見つけたいと考えています。現在、アプリケーションの残りの部分がアクティブなままインポートを実行するために NSOperation を使用しているため、ユーザーは他のことを行うことができますが、アプリ全体にすぐにアクセスできるように、インポートをできるだけ早く実行したいと考えています。 。
私が現在使用している方法は、NSFetchRequest を使用してデータ ストア内の関連エンティティの検索を試みることです。エンティティが存在する場合はそれを関係として追加し、エンティティが存在しない場合は新しいエンティティを作成します。それを関係として追加します。これは機能しますが、おそらく最適には程遠いような気がします。
私が今使用しているコード:
- (void)importEntitiesIntoContext: (NSManagedObjectContext*)managedObjectContext
{
// Setup the database object
static NSString* const databaseName = @"DBName.sqlite";
NSString* databasePath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent: databaseName];
sqlite3* database;
// Open the database from the user's filessytem
if ( sqlite3_open_v2( [databasePath UTF8String], &database, SQLITE_OPEN_READONLY, NULL ) == SQLITE_OK )
{
// Setup the SQL Statement
NSString* sqlStatement = [NSString stringWithFormat: @"SELECT some_columns FROM SomeTable;"];
sqlite3_stmt* compiledStatement;
if ( sqlite3_prepare_v2( database, [sqlStatement UTF8String], -1, &compiledStatement, NULL ) == SQLITE_OK )
{
// Create objects to test for existence of exercises
NSPredicate* predicate = [NSPredicate predicateWithFormat: @"something == $SOME_NAME"];
NSEntityDescription* entityDescription = [NSEntityDescription entityForName: @"SomeEntity"
inManagedObjectContext: managedObjectContext];
NSFetchRequest* fetchRequest = [[[NSFetchRequest alloc] init] autorelease];
[fetchRequest setEntity: entityDescription];
// Loop through the results and add them to the feeds array
while ( sqlite3_step( compiledStatement ) == SQLITE_ROW )
{
NSString* someName = [NSString stringWithCharsIfNotNull: (char*)sqlite3_column_text( compiledStatement, 1 )];
NSPredicate* localPredicate = [predicate predicateWithSubstitutionVariables:
[NSDictionary dictionaryWithObject: someName
forKey: @"SOME_NAME"]];
[fetchRequest setPredicate: localPredicate];
NSError* fetchError;
NSArray* array = [managedObjectContext executeFetchRequest: fetchRequest
error: &fetchError];
if ( array == nil )
{
// handle error
}
else if ( [array count] == 0 )
{
SomeEntity* entity =
[NSEntityDescription insertNewObjectForEntityForName: @"SomeEntity"
inManagedObjectContext: managedObjectContext];
entity.name = someName;
// **here I call a method that attempts to add the relationships(listed below)**
}
else
{
// Some entity already in store
}
}
}
else
{
NSLog( @"sqlStatement failed: %@", sqlStatement );
}
// Release the compiled statement from memory
sqlite3_finalize( compiledStatement );
}
// All the data has been imported into this temporary context, now save it
NSError *error = nil;
if ( ![managedObjectContext save: &error] )
{
NSLog( @"Unable to save %@ - %@", [error localizedDescription] );
}
}
関係を追加する方法:
- (void)setRelationshipForEntity: (Entity*)entity
inManagedObjectContext: (NSManagedObjectContext*)managedObjectContext
usingDatabase: (sqlite3*)database
entityId: (NSNumber*)entityId
{
// Setup the SQL Statement and compile it for faster access
NSString* sqlStatement = [NSString stringWithFormat: @"SELECT Relationship.name FROM Relationship JOIN Entitys_Relationship ON Entitys_Relationship.id_Relationship = Relationship.id JOIN Entitys ON Entitys_Relationship.id_Entitys = Entitys.id WHERE Entitys.id = %d;", [entityId integerValue]];
sqlite3_stmt* compiledStatement;
if ( sqlite3_prepare_v2( database, [sqlStatement UTF8String], -1, &compiledStatement, NULL ) == SQLITE_OK )
{
// Create objects to test for existence of relationship
NSPredicate* predicate = [NSPredicate predicateWithFormat: @"relationshipName == $RELATIONSHIP_NAME"];
NSEntityDescription* entityDescription = [NSEntityDescription entityForName: @"EntityRelationship"
inManagedObjectContext: managedObjectContext];
NSFetchRequest* fetchRequest = [[[NSFetchRequest alloc] init] autorelease];
[fetchRequest setEntity: entityDescription];
while ( sqlite3_step( compiledStatement ) == SQLITE_ROW )
{
NSString* relationshipName = [NSString stringWithCharsIfNotNull: (char*)sqlite3_column_text( compiledStatement, 0 )];
NSPredicate* localPredicate = [predicate predicateWithSubstitutionVariables:
[NSDictionary dictionaryWithObject: relationshipName
forKey: @"RELATIONSHIP_NAME"]];
[fetchRequest setPredicate: localPredicate];
NSError* fetchError;
NSArray* array = [managedObjectContext executeFetchRequest: fetchRequest
error: &fetchError];
if ( array == nil )
{
// handle error
}
else if ( [array count] == 0 )
{
EntityRelationship* entityRelationship =
[NSEntityDescription insertNewObjectForEntityForName: @"EntityRelationship"
inManagedObjectContext: managedObjectContext];
entityRelationship.relationshipName = relationshipName;
[entity addRelationshipObject: entityRelationship];
//NSLog( @"Inserted relationship named %@", relationshipName );
}
else
{
[entity addRelationship: [NSSet setWithArray: array]];
}
}
}
else
{
NSLog( @"slqStatement failed: %@", sqlStatement );
}
// Release the compiled statement from memory
sqlite3_finalize( compiledStatement );
}
解決
ここで、元のデータベースから来ていますか?
一般的に、あなたは開発中のコアデータにすべてのデータを変換して、事前にコアデータストア(輸入を待つために、ユーザは必要ありません)。
でアプリを出荷します他のヒント
Apple は、Core Data Store への大規模なインポートを最適化する方法についていくつかの提案をしています。
- バッチインポート中にアンドゥマネージャーを無効にする
- レコードごとに挿入しない - サイズ n のバッチを作成します (レコード サイズに応じて)
- ローカルの自動解放プールを使用し、各バッチの後にそれを排出します
を参照してください。 ドキュメンテーション 詳細については。
所属していません StackOverflow