我刚开始学习核心数据编程。我试图做一个例子,其中有一个显示人员列表(属性:名字,姓氏)的表视图。表视图依赖于NSFetchResultController来显示人员列表。核心数据多线程和嵌套上下文
我跟着嵌套上下文图案如下:
根上下文(NSPrivateQueueConcurrencyType)< --->主上下文(NSMainQueueConcurrencyType)< --->儿童上下文(NSPrivateQueueConcurrencyType)。
子上下文用于执行巨大的插入/获取(使用perormBlock:方法)。 当我尝试执行一个巨大的插入(约5000行)时,保存子上下文,然后保存主上下文,然后根上下文,我看到我的用户界面被阻止,直到保存完成。
任何人都可以告诉我为了创建高性能应用程序,采用何种最佳解决方案?任何人都可以请我提供一个很好的简单代码,展示如何在不阻止用户界面的情况下在后台进行巨大的读取/插入操作?
[_indicator startAnimating];
NSManagedObjectContext *aContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSPrivateQueueConcurrencyType];
aContext.parentContext = [[SDCoreDataController sharedInstance] mainManagedObjectContext];
[aContext performBlock:^{
NSError *error;
for (int i = 0; i < 5000; i++)
{
FootBallCoach *backgroundCoach = [NSEntityDescription insertNewObjectForEntityForName:@"FootBallCoach" inManagedObjectContext:aContext];
backgroundCoach.firstName = [NSString stringWithFormat:@"José %i",i];
backgroundCoach.lastName = [NSString stringWithFormat:@"Morinho %i",i];
backgroundCoach.cin = [NSString stringWithFormat:@"%i",i];
if (i % 50 == 0)
{
[aContext save:&error];
[aContext reset];
}
}
[[SDCoreDataController sharedInstance] saveMainContext];
[[SDCoreDataController sharedInstance] saveRootContext];
dispatch_async(dispatch_get_main_queue(), ^{
[_indicator stopAnimating];
[self refreshCoaches:nil];
});
}];
https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/CoreData/Concurrency.html –