Thomas Bødker
Thomas Bødker

Reputation: 3

What happens when NSTimer kicks in

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?

Upvotes: 0

Views: 82

Answers (1)

Joride
Joride

Reputation: 3763

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.

Upvotes: 2

Related Questions