8

NSManagedObjectContext's have had the performBlock: and performBlockAndWait: methods added to help make concurrency easier. I've been using them -- potentially fairly naively -- and I just realized that there's a question I've never really asked.

If I create an NSManagedObject subclass inside one of the performBlock methods, it's 'home' thread is the thread of it's parent context -- which in the case of the NSPrivateQueueConcurrencyType is probably an independent thread I have no other access to.

So do I need to do a performBlock call just to access the data contained inside my managed objects? Or is there a background magic going on to help protect me in the case of using getters? (Or setters, though that seems like a bad idea...)

2 Answers 2

16

NSManagedObject is not supposed to be used outside of its managedObjectContexts thread/queue (sometime it works and some times you crash ==> don't do it).

CoreData does not guarantee safe read access to the object.

To access an object owned by a "private queue" context, always use either [context performBlock:...] or [context performBlockAndWait:...], unless you access its objectID or managedObjectContext properties.

2
  • Thanks, pretty much what I was thinking was necessary... I was hoping I was wrong. I need to re-watch the WWDC video where they introduced the technique, because I don't remember them having to do that... Then again, I suspect there are a lot of WWDC videos that I need to re-watch.
    – RonLugge
    May 20, 2013 at 3:06
  • 1
    I'd just like to add that Apple engineers explicitly state that reads on NSManagedObject are not thread-safe because core data does caching, and cache writes are not thread safe Jun 18, 2013 at 5:57
9

You do need to use performBlock: or performBlockAndWait:, but there's one exception. If you're using NSMainQueueConcurrencyType and you are using the managed object on the main queue, you can access it directly, with no block. This can be a great convenience when you need to update your UI from a managed object, or vice versa.

2
  • 1
    Another exception is NSConfinementConcurrencyType which is similar to main queue, only to a specific thread (the "old" version of managed contexts)
    – Dan Shelly
    May 20, 2013 at 18:43
  • I guess I should have worded my question better, since it essentially ONLY pertains to NSPrivateQueue and NSMainQueue types... the even then, primarily to the private queue version thanks to this wonderful exception.
    – RonLugge
    May 21, 2013 at 19:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.