Reputation: 12808
I have setup few methods to load core data in the background using NSOperationQueue, like the below:
operation = [[NSInvocationOperation alloc] initWithTarget:self
selector:@selector(selectToLoadDataOne) object:nil];
operation = [[NSInvocationOperation alloc] initWithTarget:self
selector:@selector(selectToLoadDataTwo) object:nil];
The "selectToLoadDataOne" and "selectToLoadDataTwo" is just standard NSFetchRequest using the template NSManagedContext from app delegate. Problem is that after loading a few times, it just stop loading altogether and stuck at executeFetchRequest: and without any error.
I know this is related to using of threads with core data, and so I tried to create a new nsmanagedobjectcontext for each call but the result returned are empty nsmanagedobject.
Can someone point me to a good example or doc I can use to solve the loading of core data from background thread?
Upvotes: 0
Views: 533
Reputation: 46718
Core Data has very specific rules about running on multiple threads. You must have one NSManagedObjectContext
per thread and the thread that a NSManagedObjectContext
will be used on must be the thread that creates it.
You are running into issues because you are breaking that rule.
Instead of using a NSInvocationOperation
:
NSOperation
NSPersistentStoreCoordinator
NSManagedObjectContext
in the -mainOf course that is only going to load them into the NSPersistentStoreCoordinator
and you are still going to need to reload them in the main NSManagedObjectContext
.
Why do you need to load data on a background thread? Looking to speed up data loads is usually indicative of a deeper issue in the app.
Upvotes: 1