Ios 从internet下载coredata后在coredata中插入数据时GUI冻结
当我从互联网下载大数据(使用url分页)并将其保存在核心数据中时,我面临一个问题。在保存数据期间,我的应用程序GUI将冻结。保存数据后,我的应用程序工作正常。我需要你帮助我如何删除应用冻结问题 我正在使用异步的委托方法下载数据。在Ios 从internet下载coredata后在coredata中插入数据时GUI冻结,ios,objective-c,cocoa-touch,core-data,Ios,Objective C,Cocoa Touch,Core Data,当我从互联网下载大数据(使用url分页)并将其保存在核心数据中时,我面临一个问题。在保存数据期间,我的应用程序GUI将冻结。保存数据后,我的应用程序工作正常。我需要你帮助我如何删除应用冻结问题 我正在使用异步的委托方法下载数据。在connectiondFinishLoading方法中,我将数据插入核心数据。这是connectiondFinishLoading方法中的代码 [Customer insertCustomerWithList:数据] [self.delegate connectPerm
connectiondFinishLoading
方法中,我将数据插入核心数据。这是connectiondFinishLoading
方法中的代码
[Customer insertCustomerWithList:数据]代码>
[self.delegate connectPermissionServiceSuccessful:method]代码>
在这里,insertCustomerWithList
方法应用程序被冻结。
如果我使用dispatch\u async
GCD方法,那么应用程序会因为给出此错误而开始崩溃
错误***集合在
正在枚举。
这是GCD的代码
dispatch_queue_t coreDataThread = dispatch_queue_create("com.YourApp.YourThreadName", DISPATCH_QUEUE_CONCURRENT);
dispatch_async(coreDataThread, ^{
[Customer insertCustomerWithList:data];
dispatch_async(dispatch_get_main_queue(), ^{
[self.delegate connectPermissionServiceSuccessful:kMethod];
});
});
这是将数据插入核心数据的insertCustomerWithList
方法
+(BOOL)insertCustomerWithList:(NSArray*)customerList
`{NSError *error = nil;
BOOL success = YES;
Customer *obj = nil;
NSManagedObjectContext *managedObjectContext = [NSManagedObjectContext managedObjectContext];`
if (managedObjectContext == nil)
{
success = NO;
}
@try
{
for (NSInteger index = 0; index < customerList.count ; index ++)
{
NSDictionary* customerInfo = customerList[index];
obj = [self getCustomerByID:customerInfo[@"_id"]];
if (obj == nil)
{
obj = [NSEntityDescription insertNewObjectForEntityForName:kEntityName
inManagedObjectContext:managedObjectContext];
[obj updateCustomer:customerInfo];
}
else
{
[obj updateCustomer:customerInfo];
}
}
}
@catch (NSException *exception)
{
NSLog(@"__ERROR__%@__", exception.reason);
}
[managedObjectContext save:&error];
return success;
`}`
`{NSError*error=nil;
布尔成功=是;
客户*obj=nil;
NSManagedObjectContext*managedObjectContext=[NSManagedObjectContext managedObjectContext]`
if(managedObjectContext==nil)
{
成功=否;
}
@试一试
{
对于(NSInteger index=0;index
请帮助我解决此问题 您应该使用NSManagedObjectContext
的performBlock
api,而不是创建自己的线程
以下设置不会阻止您的UI:
Root context (background) - save to persistent store
Main context (foreground) - child of Root, used on UI
Worker context (background) - child of Main, do heavy loading
web调用的结果块应创建工作上下文并插入新数据。然后save()
方法将把更改“推”到主上下文中,因此如果您的UI需要显示新数据,这已经是可能的了。主上下文的save()
将更改推送到根上下文,只有在根上下文上调用save()
时,更改才会写入数据库
在后台操作中使用块API,您会很好。很难给出具体的答案,因为您没有显示核心数据堆栈的排列方式
对于基本应用程序,最简单的方法是创建连接到持久存储的持久背景上下文(NSPrivateQueueConcurrencyType
)。对于主线程,使用NSMainQueueConcurrencyType
创建后台上下文的子线程
您可以通过发出performBlock
消息在后台上下文中进行编写。通过设置NSFetchedResultsController,可以在子上下文中通知您。主题外:您不应该使用异常处理。