0
votes

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

2
Why do you want to know the thread?Amin Negm-Awad
The error seams that we need know the thread.I am Sophia
No, the error talks about queues, not threads. Did you read the multithreading programming guide fr Core Data?Amin Negm-Awad
Yeh, may be I need do some research. Just mark it....I am Sophia

2 Answers

0
votes

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.

0
votes

The error does not say that you are using the wrong thread. It says that you can use -performBlock: only on contexts that are created with a queue. As described in the class reference of NSManagedObjectContext/Concurrency, this are only the contexts that are created with one of the options NSPrivateQueueConcurrencyType or NSMainQueueConcurrencyType set.

You use contexts using the queue-based concurrency types in conjunction with performBlock: and performBlockAndWait:.