实际上,我已经实现了后台同步调用,它使用CoreData将数据存储在本地数据库中。我收到了数千条记录,但是应用程序在一段时间后崩溃并发出错误
EXC_BAD_ACCESS代码1.
也许是因为NSManagedObjectContext
而发生的,不确定。这是我的代码:
-(void)RestClient:(RestClient *)client didCompleteWithSuccess:(id)responseObject withLastModifiedDate:(NSString *)lastModifiedDate{
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(void) {
@try {
if(responseObject!=nil){
NSError *error = nil;
NSDictionary *jsonResponse = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:&error];
if (!error) {
int totalrecords = [[jsonResponse objectForKey:@"records"] intValue];
if(totalrecords>0){
NSManagedObjectContext * manageObjContext = [Common getBkgManagedObjectContext];
NSArray* rows = [jsonResponse objectForKey:@"rows"];
for(NSString* email in rows){
[NotifyEmails insertIntoNotifyEmails:email withManagedObjectContext:manageObjContext];
}
NSError *error = nil;
if (![manageObjContext save:&error]) {
NSLog(@"Data couldn't save: %@", [error localizedDescription]);
}
}
}
}
}@catch (NSException *exception) {
NSLog(@"exception in rest response");
NSLog(@"Error :: %@",exception);
}@finally {
[self finishOperation];
}
});
}
NsmanagedObjectContext函数:
- (NSManagedObjectContext *)getBkgManagedObjectContext {
NSManagedObjectContext *manageObjCtx;
NSPersistentStoreCoordinator *coordinator = [(EMAINTAINAppDelegate *)[[UIApplication sharedApplication] delegate] persistentStoreCoordinator];
if (coordinator != nil) {
manageObjCtx = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSPrivateQueueConcurrencyType];
[manageObjCtx setPersistentStoreCoordinator:coordinator];
}
return manageObjCtx;
}
答案 0 :(得分:1)
ManagedObjectContext
不是线程安全的。至关重要的是要知道每个上下文要运行哪个线程。使用NSPrivateQueueConcurrencyType
创建的上下文捆绑了一个私有线程,您只能通过performBlock
或performBlockAndWait
访问(换句话说,队列是PRIVATE)。在任何其他线程上访问上下文是不安全的 - 甚至是后台线程。上下文没有附加到它创建的线程上(正如你似乎假设的那样),这就是NSConfinementConcurrencyType
的行为,现在已弃用。