We have a background thread that needs to do some fetching.. but it doesnt need any data — only the objectIDs
originally we did this using a specific newly created blank managed context just for this.
NSFetchRequest *request = [DKDocumentDetails requestAllWithPredicate:predicate inContext:ctx];
[request setResultType:NSManagedObjectIDResultType];
self.objectIDs = [DKDocumentDetails executeFetchRequest:request inContext:ctx];
...
but recently I found out, I can also do this on the PST itself, without any context AS I dont want Managed Objects, but only IDs
NSFetchRequest *request = [DKDocumentDetails requestAllWithPredicate:predicate inContext:mainctx /*used in the wrong thread but only for getting entity description*/];
[request setResultType:NSManagedObjectIDResultType];
NSError *error = nil;
self.objectIDs = [pst executeRequest:request inContext:nil error:&error];
...
so in my tests it never crashed and in the docs I dont see why it shouldnt work either… I mean I dont get unsaved stuff and I cannot get objects, but used this way…
It is faster and looks elegant but is it safe or not?
I’ve been thinking about your question all day. Here is what I’ve come up with. As others have pointed out,
NSPersistentStoreCoordinatorobjects are not thread safe. When a bunch ofNSManagedObjectContextobjects on various threads use the sameNSPersistentStoreCoordinator, they do so by locking and unlocking theNSPersistentStoreCoordinator.However, you are worried about just reading data, and thread safe
NSManagedObjectIDdata at that. Is that ok?Well, the Apple documentation On Concurrency with Core Data mentions something similar to what you are doing:
Ok, but do we need to lock the Coordinator?
That seems to be pretty clear that if you are performing operations on a persistent store from more than one thread, you should lock it.
But wait – these are just read operations, shouldn’t they be safe? Well, apparently not:
Its the cache we need to worry about. That’s why you need to lock – a read in one thread can cause data in another thread to get messed up through inadvertent cache changes. Your code never gave you problems because this is probably really rare. But its those edge cases and 1-in-1,000,000 bugs that can do the most damage…
So, is it safe? My answer: