Iphone CoreData应用程序在执行获取请求pthread\u mutex\u lock时冻结
我正在使用核心数据在我的应用程序中管理数据库 我不能在这里发布代码,因为它太长了。但我想我可以用一小行代码和一些快照来解释我的问题Iphone CoreData应用程序在执行获取请求pthread\u mutex\u lock时冻结,iphone,ios,multithreading,ios5,core-data,Iphone,Ios,Multithreading,Ios5,Core Data,我正在使用核心数据在我的应用程序中管理数据库 我不能在这里发布代码,因为它太长了。但我想我可以用一小行代码和一些快照来解释我的问题 +(NSArray *)checkusernameandpassword:(NSString *)entityname username:(NSString *)username password:(NSString *)password { managedobjectcontext=[Singleton sharedmysingleton].man
+(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;
}
我正在尝试附加呼叫堆栈的一些屏幕截图(这些截图是我在暂停应用程序时看到的)
上面提到了在图像中带有复选标记的方法,在该方法出现死锁时
您必须锁定线程。当多个线程访问同一段代码时,就会出现此问题。但我们最终不会陷入死锁
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上下文不是线程安全的,正确使用它是您的责任 非常详尽 上面提出的解决方案根本不安全:如果您在并发环境中编程(即,我们假设您有多个线程可以并发访问同一个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
...
});
您可以尝试
[private performBlock:^{}]代码>在多线程环境中使用核心数据时
有关更多详细信息,请查看此文档Hello@AlexTerente,您是否介意查看并告诉我您的解决方案是否也适用于该文档?