简体   繁体   中英

Is the save: method thread-safe?

In short

Can I call

[moc performBlockAndWait:^{
    [moc save:NULL] ;
}];

from different threads at the same time?

In long

I add a crash similar to this one , namely:

Serious application error.  Exception was caught during Core Data change processing.  This is usually a bug within an observer of NSManagedObjectContextObjectsDidChangeNotification.  -[__NSCFSet addObject:]: attempt to insert nil with userInfo (null)
2011-06-15 11:36:59.864 myApp[457:607] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFSet addObject:]: attempt to insert nil'
*** Call stack at first throw:

The program crashes on this command:

[moc performBlockAndWait:^{
    [moc save:NULL] ;
}];

As I launch the same process (with difference parameters) to as many threads as possible (with the help of NSOperationQueue ), this command might be called by different threads as the same time.

Could that be a problem? Or the method performBlockAndWait: already deals with that?

I ask you the question to know if I need to create a singleton that would manage the saving to the moc.

-save: must be called from the thread/queue that created the context.

calling -performBlockAndWait: does avoid calling it from the wrong thread.

  1. You must pass in a NSError to the -save: method and you need to watch the result of the -save: to determine if an error is occurred. That is your singular way of knowing if an error occurred. Passing in NULL is asking for trouble.

  2. The error you are currently seeing is not caused from the save directly. It is most likely caused because you are listening to NSManagedObjectContextDidSaveNotification somewhere else and doing something incorrect there. Search your code for that constant and review the code associated with it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM