2012-07-24 22 views
3

我正在使用Core Data来管理数据库到我的应用程序中。CoreData Application在执行提取请求时冻结pthread_mutex_lock

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

+(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; 
} 

我试图连接的呼叫组的一些屏幕截图(这些我看到在我暂停应用程序) 与图像中的选中标记的方法,在此僵局上述 提到发生The method with a checkmark in the image,at which deadlock occur is mentioned above

回答

3

您必须锁定线程。多线程访问同一段代码时出现此问题。但是最终不会陷入死锁。

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; 
+0

你好@AlexTerente,你能不能考虑看看[本问题](http://stackoverflow.com/questions/23504936/core-data-executefetchrequest-冻结应用程序中的后台线程)并告诉我您的解决方案是否也适用于此? – mirx 2014-05-07 07:47:56

0

据我的理解,你可以从你的转储中,调用除了MainThread以外的其他线程中的CoreData Context。

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

Apple documentation about CoreData and Thread非常详尽。

上面提出的解决方案是不是安全可言:synchronized语句是无用的,如果你是在一个并行编程环境(即你有一个以上的线程,我们认为可以同时访问同一个MOC)。

你可以尝试“限制”线程生命周期内的环境。例如:

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 
... 
});