2012-07-24 77 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 
... 
});