使用,当我遇到有趣的行为来的NSManagedObjectContext的performBlock:与通知中心.
从主UI线程我触发异步数据下载(使用NSURLConnection的connectionWithRequest:).当数据到达时,将调用以下委托方法:
- (void)downloadCompleted:(NSData *)data
{
NSArray *new_data = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
self.backgroundObjectContext = [[NSManagedObjectContext alloc]
initWithConcurrencyType:NSPrivateQueueConcurrencyType];
self.backgroundObjectContext.persistentStoreCoordinator = self.persistentStoreCoordinator;
[self.backgroundObjectContext performBlockAndWait:^{
[self saveToCoreData:new_data];
}];
}
Run Code Online (Sandbox Code Playgroud)
该savetoCoreData:方法只是将新数据保存到后台上下文:
- (void)saveToCoreData:(NSArray*)questionsArray
{
for (NSDictionary *questionDictionaryObject in questionsArray) {
Question *newQuestion = [NSEntityDescription
insertNewObjectForEntityForName:@"Question"
inManagedObjectContext:self.backgroundObjectContext];
newQuestion.content = [questionDictionaryObject objectForKey:@"content"];
}
NSError *savingError = nil;
[self.backgroundObjectContext save:&savingError];
}
Run Code Online (Sandbox Code Playgroud)
在视图控制器中,viewDidLoad我将观察者添加到通知中心:
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(contextChanged:)
name:NSManagedObjectContextDidSaveNotification
object:nil];
Run Code Online (Sandbox Code Playgroud)
然后在contexChanged:我合并背景上下文与主上下文,以便调用我的NSFetchedResultsController的委托方法,我的视图可以更新:
- (void)contextChanged:(NSNotification*)notification
{ …Run Code Online (Sandbox Code Playgroud) core-data nsfetchedresultscontroller nsnotificationcenter nsmanagedobjectcontext ios