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
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 the only purpose is to be able to access
self.myString; //getter
and,
self.myString=aString; //setter
The best way is to declare it as atomic, for example:
@property (atomic, strong) NSString* myString;
This will ensure that in a multithreaded environment, setting and getting myString by thread 1 is protected from thread 2 doing something to it.