2

I want to use Core Data in background threads and NSOperationQueue. Now I thought why shouldn't I just create a class holding all the Core Data stack things with a property of NSManagedObjectContext, and then just make this property atomic?

One thing I'm not sure about @synchronize(self) {...} is this: Assume I have a property that's considered thread-safe:

@property (retain) NSManagedObjectContext *moc;

Every NSOperation or thread accesses an CoreDataTools class which has this moc property. They access this moc property like this:

// Assume: Inside an NSOperation or new thread here...
NSManagedObjectContext *moc = [[CoreDataTools sharedInstance] moc];

// Do a lot of things with moc. Add and remove 20 objects.

Would this be effective at all? I don't understand WHEN this lock is effective. Just in the event of actually accessing the property? Or can I safely work with the NSManagedObjectContext instance until the NSOperation or called method of the background thread is done and returns?

I know NSMangagedObjectContext has a -lock method. I want to know in general if this would work or not.

Proud Member
  • 40,078
  • 47
  • 146
  • 231

2 Answers2

4
 @synchronized(self) { /* lock is effective inside here only */ } 
Rayfleck
  • 12,116
  • 8
  • 48
  • 74
  • 2
    Also, if you really need to lock something, `@synchronized()` is about the slowest way to go: http://perpendiculo.us/?p=133 . – Brad Larson Jun 01 '11 at 17:33
  • 1
    @Brad Larson - 100 million locks in 10 seconds. I don't think that's all too slow. – rein Aug 12 '12 at 15:54
2

No. Each thread should have its own managed object context.

More info: Concurrency with Core Data

TheBlack
  • 1,245
  • 1
  • 8
  • 12
  • How about the mechanics of @synchronize in general? – Proud Member Jun 01 '11 at 14:29
  • THe subject is pretty broad to be explained in a whole here but in general @synchronize is recursive lock and can degrade performance if that's what you're after. NSCondition in that regard is much better option. – TheBlack Jun 01 '11 at 15:10