2016-07-17 10 views
2

コアデータを同時に正しく使用する方法を見つけるのが難しいです。コアデータ、同時実行性、GCD

更新があるたびに新しいデータを追加する前に、エンティティのコアデータをクリアする必要があります。そこで私は、このスニペットを使用することにしました:

-(void)addSale:(NSArray *)results{ 

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ 

    NSString *entity = @"Sale"; 

    CoreDataManager.sharedInstance.delegate = self; 

    dispatch_async(dispatch_get_main_queue(), ^{ 
     [CoreDataManager.sharedInstance deleteEntityWithName:entity]; 
    }); 

    NSManagedObjectContext *privateContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSPrivateQueueConcurrencyType]; 
    privateContext.parentContext = CoreDataManager.sharedInstance.managedObjectContext; 

    for (NSDictionary *dataDictionary in [results valueForKey:@"Sales"]) 
    { 
     NSManagedObject *managedObject = [NSEntityDescription insertNewObjectForEntityForName:entity inManagedObjectContext:privateContext]; 


     // Fill ManagedObject 
     // ..... 

    } 

    NSError *error; 
    [privateContext save:&error]; 

    if (error != nil) { 
     NSLog(@"Couldn't save private context bcoz of %@\n%@", error, error.localizedDescription); 
    } 

    dispatch_async(dispatch_get_main_queue(), ^{ 
     // Save Main ManagedObjectContext 
     [CoreDataManager.sharedInstance saveContext:CoreDataManager.sharedInstance.managedObjectContext WithEntityName:entity]; 
    }); 
}); 
} 

問題は、私はコアデータ上の任意の影響をせずに応答UIを維持しながら2つの他のエンティティのために同じことをしなければならないということです。

これを処理する方法はありますか?

答えて

2
  1. NSPersistentStoreCoordinatorに関連付けられたプライベートコンテキストを作成します。
  2. プライベートコンテキストでオブジェクトを削除します。
  3. プライベートコンテキストを保存します。
  4. これらのオブジェクトのいずれかが使用されていた場合、メインキューコンテキストにリセットを指示します。

(あなたがあなたのシングルトンでやっていると思われる)メインのコンテキスト上のオブジェクトを削除する理由は本当にありません。

削除しているオブジェクトにUIが触れていない場合は、ユーザーインターフェイスに関連付けられたコンテキストをリセットする必要はありません。

リセットを実行する代わりに、メインキューコンテキストがプライベートキューコンテキストからの保存通知を消費し、同じ結果を得ることもできます。

関連する問題