1

I'm having an issue related to objectIDs used in a multi-threaded context.

I am using objectIDs to pass an entity a completion block that's called by a background thread, like so :

   NSManagedObjectID *entityID = [entity objectID];
   [self.queue enqueue:
    ^{
       NSManagedObjectContext *managedObjectContext = // child moc on a bg thread
       Entity *entity = (Entity *)[managedObjectContext objectWithID:entityID];

       /* Work using the entity */
     }];

This used to work fine until I started deleting entities while network requests are ongoing ( Unfortunately, i cannot simply cancel them), which made me run into CoreData unresolved fault errors.

In order to fix this issue, I started using NSManagedObjectContext's existingObjectWithID: method instead. The advantage is that it will return nil if the object doesn't exist, but I ran into a different issue : existingObjectWithID will return nil if the objectID is temporary, although the object truly exists.

I tried using obtainPermanentIDsForObjects when entities are created, but this isn't ideal since it implies some work with the persistence store, and randomly crashes.

Is there a proper way to check that an entity still exists upon the completion of an asynchronous network request ?

Thanks in advance !

Toop
  • 11
  • 1
  • 1
    If the object "truly" exists, it should be part of a context and therefore have an ID, so it should be returned correctly from `existingObjectWithID:`. – Mike Weller May 02 '13 at 09:55
  • When you say "multi-threaded context", are you using the same managed object context on multiple threads? Are you using one of the queue concurrency types and making sure to use `performBlock:` or `performBlockAndWait:`? – Tom Harrington May 02 '13 at 16:20
  • Related discussion: http://stackoverflow.com/questions/16235757/how-to-handle-saving-on-child-context-but-the-objected-is-already-deleted-in-par/16236432#16236432 – Christian Kienle May 02 '13 at 16:46
  • I assumed that it would be returned by the existingObjectWithID: method but this is not the case when the object is temporary, probably because it has been saved by the time the network request finishes. The entity is nil and the following error is raised : `(0x210f85c0 ): Error Domain=NSCocoaErrorDomain Code=133000 "The operation couldn’t be completed. (Cocoa error 133000.)"` – Toop May 07 '13 at 08:59

0 Answers0