Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you use an NSManagedObject outside of it's context's performBlock?

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...)

like image 220
RonLugge Avatar asked May 20 '13 02:05

RonLugge


2 Answers

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.

like image 73
Dan Shelly Avatar answered Nov 13 '22 00:11

Dan Shelly


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.

like image 21
Tom Harrington Avatar answered Nov 13 '22 01:11

Tom Harrington