私は、NSFetchedResultsController とそれに接続されたメイン コンテキストを備えた UITableView を持っています。メインコンテキストをバックグラウンドから更新しています。
- (void)contextDidSave:(NSNotification *)notification
{
NSManagedObjectContext *context=[self managedObjectContext];
[context performSelectorOnMainThread:@selector(mergeChangesFromContextDidSaveNotification:) withObject:notification waitUntilDone:YES];
if ([context hasChanges])
{
[context performSelectorOnMainThread:@selector(save:) withObject:nil waitUntilDone:YES];
}
}
私の UITableView は新しいデータでリロードされ、すべて問題ありませんが、一部の UITableView セルのデータはフェッチされたプロパティから入力する必要があり、その値を更新する必要があります。
NSManagedObjectContext のメソッド refreshObject:mergeChanges: について読んだことがあります。どこに置けばいいですか?それを cellForRowAtIndexPath のヘルパー メソッド - configureCell:atIndexPath: に配置すると、行の更新が繰り返されます。
セル構成コードの一部を次に示します。
- (void)configureCell:(UITableViewCell *)cell atIndexPath:(NSIndexPath *)theIndexPath
{
//NSLog(@"PTAgencyList: configureCell: atIndexPath: %i %i", theIndexPath.section, theIndexPath.row);
NSManagedObject *managedObj=[self.agenciesFetchedResultsController objectAtIndexPath:theIndexPath];
if (managedObj==nil)
{
NSLog(@"PANIC: fetchedResultsController objectAtIndexPath: returned nil object");
return;
}
else
{
CDAgency *agency=(CDAgency *)managedObj;
[agency city];
NSLog(@"agency.city_server_id: %@", agency.city_server_id);
NSLog(@"agency.city.name: %@", ((CDCities *)[[agency city] objectAtIndex:0]).name);
NSFetchRequest *fr=[[NSFetchRequest alloc] init];
[fr setEntity:[NSEntityDescription entityForName:@"Cities" inManagedObjectContext:self.context]];
[fr setPredicate:[NSPredicate predicateWithFormat:@"server_id=%@", agency.city_server_id]];
NSArray *res=[self.context executeFetchRequest:fr error:nil];
NSLog(@"fetched city name: %@", ((CDCities *)[res objectAtIndex:0]).name);
コンテキストの更新後: フェッチされたプロパティ city は nil です (削除された古い都市エントリをまだ指しているためだと思います)が、手動でフェッチを行っている場合は新しいデータを取得しています。