0

I know that you should abide by CoreData's thread confinement rules in general, but is it ever safe to use -[NSManagedObjectContext lock] and friends? I know that accessing an NSManagedObject property can trigger an implicit NSManagedObjectContext fetch if the NSManagedObject has unloaded properties, so I assume you would have to wrap all NSManagedObject property accesses around -[NSManagedObjectContext lock] and -[NSManagedObjectContext unlock]. I thought this was the only gotcha. Are there others?

In the comments of this answer, Marcus Zarra says that I'm misinterpreting the documentation about -\[NSManagedObjectContext lock\] and friends:

Sending this message to a managed object context helps the framework to understand the scope of a transaction in a multi-threaded environment. It is preferable to use the NSManagedObjectContext’s implementation of NSLocking instead using of a separate mutex object.

Also, the above quote implies that you can use other locks to guard NSManagedObjectContext. Is this true?

I'm not worried about parent/child contexts for this question.

Community
  • 1
  • 1
Heath Borders
  • 30,998
  • 16
  • 147
  • 256

1 Answers1

3

In an academic setting, can you use locks? yes.

Should you ever use them in production code? no. Why? Because the odds of getting it right the first time are extra-ordinarily high. Getting it right in maintenance mode rapidly approaches zero.

Using locks to access Core Data is just asking for trouble. When you get it wrong you lose/corrupt data. When you get it right you are breaking even with thread confinement. It is a lose/lose gamble with nothing to gain.

The worst part is that there is virtually no way to know if you got it "right" until or unless you lose data. Never worth the risk.

I would also point you to this response from Ben which should give you some nice history on this subject.

Community
  • 1
  • 1
Marcus S. Zarra
  • 46,571
  • 9
  • 101
  • 182