3

我正在使用 Core Data 将数据库管理到我的应用程序中。

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

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

我正在尝试附加一些调用堆栈的屏幕截图(当我暂停我的应用程序时会看到这些屏幕截图) 上面提到了图像中带有复选标记的方法,在该方法发生死锁 上面提到了图像中带有复选标记的发生死锁的方法

4

3 回答 3

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;
于 2012-07-24T14:31:35.997 回答
0

据我从您的转储中了解到,您在 MainThread 以外的不同线程中调用 CoreData Context。

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

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

上面提出的解决方案根本不安全:如果您在并发环境中编程(即您有多个线程,我们假设可以同时访问同一个 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
...
}); 
于 2015-01-16T22:33:37.627 回答
-1

[private performBlock:^{}];在多线程环境中使用 Core Data 时可以尝试。

有关更多详细信息,请查看此文档https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/CoreData/Concurrency.html#//apple_ref/doc/uid/TP40001075-CH24-SW1

于 2018-01-26T08:39:01.330 回答