I have a CoreDataUtilities class with a class method that saves a managed object context and takes care of any errors:
+ (void)saveContext:(NSManagedObjectContext*)moc {
NSError *error = nil;
if (moc != nil) {
if ([moc hasChanges] && ![moc save:&error]) {
NSLog(@"MOC save error: %@, %@", error, [error userInfo]);
}
}
}
I call this method from NSOperation subclasses and background threads, and pass in the NSManagedObjectContext instance of the thread / NSOperation.
My concern is this:
If Thread A calls this method, and while this method is executing half-way, Thread B calls it too. With another MOC of course. Woul this interfere in any way? From my point of view it would not, because this method does only communicate with the MOC instance which is “private” or “owned” by the calling Thread anyways. But what irritates me is if even local variables in a method get “mixed up” when multiple threads execute the same piece of code at the same time. Or does every variable have their own “context” in a new thread, with it’s own heap (or stack, for that matter) of memory?
Does it make a big difference if I put this saving code directly into the NSOperation subclasses and background threads? Why?
Why don’t you put a
@synchronize(...)block around the save operation. This will ensure that a managed object context won’t be saved if it’s already saving.Read here on synchronization.