What should be the best way in an iOS app to prevent an instance variable from being changed by an object while another is using it? Should the use of @synchronized(self)
directive be enough?
Thanks in advance
If you want that an object is blocked so that no two threads use it at the same time then @synchronize is one way. But this does not make it thread-safe.
You can also use GCD(Grand Central Dispatch) for the same
What should be the best way in an iOS app to prevent an instance variable from being changed by an object while another is using it?
A good old lock, such as pthread_mutex
; you could also use an Objective-C wrapper of this (e.g. NSLock
and NSRecursiveLock
). @synchronized
also falls into this category, but it is the highest level mechanism mentioned here.
Of course, superior concurrent solutions typically have more to do with changes to design, program flow, favoring immutability, and so on. There will still be cases where mutual exclusion/locking is preferred or required.
Unfortunately, pure ObjC/Cocoa are sorely lacking in this domain -- developing a highly efficient concurrent program using ObjC and Cocoa technologies alone is far more difficult than it should be (or needs to be).
Should the use of @synchronized(self) directive be enough?
For simple cases, it is adequate. It is an object level Recursive Lock.
However, it is quite slow, compared to other mutual exclusion options.
I don't think @synchronized
has much going for it, apart from:
@synchronized
is convenient, but because it has a high cost, it should be used judiciously.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With