0

I have a iOS construction where I get callbacks from an underlying class. This callback make changes to a NSMutablearray.

At the same time I have a NSTimer that makes a callback to a method that makes changes to the same NSMutable array.

I see a potential problem here if the callbacks "collide" working with the NSMutablearray.

I am not sure how to deal with this. Could NSLock do the trick or should I instantiate my NSMutablearray as atomic?

rmaddy
  • 314,917
  • 42
  • 532
  • 579
  • Are you using multiple threads? If not, the timer won't fire until the other code has finished. Timers don't fire until the next time your code returns and visits the event loop. – Duncan C Apr 27 '16 at 11:37
  • Whatever you do, keep in mind that locking alone might not solve all your problems, i.e. even if every access to the array is locked, this might not be enough to make it thread-safe. Quick example: a longer operation that needs multiple accesses to the array, but the array may have changed in between. – Eiko Apr 27 '16 at 11:44

1 Answers1

2

You should make sure that any change to the mutable array occurs on the same thread. This will make sure there can be no 'collisions'. If your timer fires on the main thread, and your callback also occurs on the main thread, everything is good.

If the timer and the callback are on different threads, you can serialize the access to the array using a serial GCD-queue. When you do this, ANY AND ALL access to this array should be done on this queue (keep a reference to this queue in a property for instance).

NSLock might help you, but if you are working on the main thread, this is usually not a good idea, as you might be blocking the main queu, which affects user-interaction / scrolling behviour.

Also, atomic only means that getting or setting the pointer to the array is thread safe, i.e.: a valid value will be returned or set (dors not mean it will be the correct value though). Any operations you do on it have nothing to do with the property being atomic or nonatomox.

Joride
  • 3,722
  • 18
  • 22