CoreData应用程序在执行提取请求pthread_mutex_lock时冻结

我正在使用核心数据pipe理数据库到我的应用程序。

我不能在这里发布代码,因为它太冗长了。 但是我想我可以用一小段代码和一些快照来解释我的问题。

+(NSArray *)checkusernameandpassword:(NSString *)entityname username:(NSString *)username password:(NSString *)password { managedobjectcontext=[Singleton sharedmysingleton].managedobjectcontext; NSEntityDescription *entity=[NSEntityDescription entityForName:entityname inManagedObjectContext:managedobjectcontext]; NSFetchRequest *request=[[NSFetchRequest alloc] init]; [request setEntity:entity]; NSPredicate *predicates=[NSPredicate predicateWithFormat:[NSString stringWithFormat:@"userName==\"%@\" AND password==\"%@\"",username,password]]; [request setPredicate:predicates]; //On Below line, My app frezes and goes into deadlock, this happens randomly while performing //some data request using Core data NSArray *arrayofrecord=[managedobjectcontext executeFetchRequest:request error:nil]; return arrayofrecord; } 

我正在尝试添加一些调用堆栈的屏幕截图(这些是我暂停我的应用程序时看到的) 上面提到了图像中出现死锁的方法 上面提到了图像中出现死锁的复选标记的方法

你必须locking线程。 当多个线程访问同一段代码时,会出现此问题。 但是不是最终死锁。

 static NSString *fetchRequest = @"fetchRequest"; NSArray *results; @synchronized (fetchRequest){ managedobjectcontext=[Singleton sharedmysingleton].managedobjectcontext; NSEntityDescription *entity=[NSEntityDescription entityForName:entityname inManagedObjectContext:managedobjectcontext]; NSFetchRequest *request=[[NSFetchRequest alloc] init]; [request setEntity:entity]; NSPredicate *predicates=[NSPredicate predicateWithFormat:[NSString stringWithFormat:@"userName==\"%@\" AND password==\"%@\"",username,password]]; [request setPredicate:predicates]; //On Below line, My app frezes and goes into deadlock, this happens randomly while performing //some data request using Core data results = [managedobjectcontext executeFetchRequest:request error:nil]; } return results; 

据我所知你的转储,你是在一个不同于MainThread的线程调用CoreData上下文。

请记住,CoreData上下文不是线程安全的,您的责任是正确使用它。

有关CoreData和Thread的Apple文档非常详尽。

上面提出的解决scheme根本不安全:如果在并行环境中进行编程(即,我们假设可以同时访问同一个MOC的多个线程),则synchronized语句是无用的。

您可以尝试在线程生命周期中“限制”您的上下文。 例如:

 dispatch_async(dispatch_get_global_queue(0, 0), ^(){ NSManagedObjectContext* context = [[NSManagedObjectContext alloc] init]; context.persistentStoreCoordinator = self.mainContext.persistentStoreCoordinator; //Make the fetch and export results to main thread ... });