Search code examples
objective-cmultithreadingcrashnsmanagedobjectcontext

'Can only use -performBlock: on an NSManagedObjectContext that was created with a queue.' Error


I use NSManagedObjectContext performBlock{} But, My app always crash here

*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Can only use -performBlock: on an NSManagedObjectContext that was created with a queue.'

How to know the right thread about the NSManagedObjectContext. The create NSManagedObjectContext code is here

Person *aPerson = (Person *)[NSEntityDescription insertNewObjectForEntityForName:@"Person" inManagedObjectContext:[CoreDataManager sharedInstance].managedObjectContext];

Please give some comments


Solution

  • Create your ManagedObjectContext like this

    NSManagedObjectContext *moc = [[NSManagedObjectContext alloc]
                         initWithConcurrencyType:NSMainQueueConcurrencyType];
    

    NSMainQueueConcurrencyType creates a context that is associated with the main dispatch queue and thus the main thread. You could use such a context to link it to objects that are required to run on the main thread, for example UI elements.

    NSPrivateQueueConcurrencyType creates and manages a private dispatch queue to operate on. You must use the new methods performBlock: or performBlockAndWait:. The context will then execute the passed blocks on its own private queue.

    Finally, NSConfinementConcurrencyType is the default type and can be used only within the thread where it has been created.