0

I have an array of NSManagedObjects, which is shared by several fragments, some on main queue some inside callback closures. Sometimes while I am clearing this array , other part of code tries to access it to read and show the data on UI and as it sometimes doesn't find data it crashes.

I am considering to use NSLocks to protect this array write or read, however I am not sure if this approach is safe and correct. I am open to suggestions , or correction to this approach.

vishal dharankar
  • 7,536
  • 7
  • 57
  • 93

1 Answers1

1

Apple does not recommend to share same NSManagedObject between different threads:

NSManagedObject instances are not intended to be passed between queues. Doing so can result in corruption of the data and termination of the application. When it is necessary to hand off a managed object reference from one queue to another, it must be done through NSManagedObjectID instances.

You should have different copies of the object on different threads.

I think in your case you have 2 problems:

  1. First problem with sharing of NSManagedObject. If NSManagedContext on one thread drops his cache you will have exception on other threads if they use NSManagedObjects from the context.
  2. You share same NSMutableArray on threads. If you remove objects from the array on one thread (data source thread) and other thread (for example UI thread) tries to get object on removed index you will have a range exception. To solve this case you should copy your array to other thread, and notify them about new data is available. You should do it because NSMutableArray is not thread safe.
Andrew Romanov
  • 4,774
  • 3
  • 25
  • 40