Another way to avoid thread conflicts (alternative to @synchronized()
), is using Grand Central Dispatch (which in the majority of cases is faster than the former):
@property (assign, nonatomic) BOOL clearCookies;
// Later in code
static dispatch_queue_t clearCookiesQueue;
- (void)setClearCookies:(BOOL)clearCookies {
[self initializeClearCookiesQueue];
dispatch_async(clearCookiesQueue, ^{ // Note, this is "async"
_clearCookies = clearCookies;
});
}
- (BOOL)clearCookies {
[self initializeClearCookiesQueue];
__block BOOL clearCookies;
dispatch_sync(clearCookiesQueue, ^{ // Note, this is "sync"
clearCookies = _clearCookies;
});
// As "sync" waits until the operation is finished, you can define
// your other operations here safely.
[self doOtherStuff];
return clearCookies;
}
/**
Checks if the queue for the clearCookies property is initialized and,
if it's not, initializes it.
*/
- (void)initializeClearCookiesQueue {
if ( ! clearCookiesQueue ) {
// We'll use a serial queue to avoid conflicts reading/writing the ivar
clearCookiesQueue = dispatch_queue_create("com.yourapp.yourviewcontroller.someUniqueIdentifier", DISPATCH_QUEUE_SERIAL); // Note, this is a C string, not NSString
}
}
If you don't care about threading, or you don't need it, just overriding your setter is enough:
- (void)setClearCookies:(BOOL)clearCookies {
_clearCookies = clearCookies;
[self doOtherStuff];
}