Last active
December 9, 2016 21:12
-
-
Save ashokds/dd04a9a5ffa170e56b9a49e77a764d77 to your computer and use it in GitHub Desktop.
Static BOOL thread safety with class methods
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Old using NSLock. | |
#import "XYZManager+Additions.h" | |
@implementation XYZManager (Additions_old) | |
static BOOL setup = NO; | |
static NSLock *setupLock = [NSLock new]; | |
+ (void)xyz_setupSuccessful:(BOOL)success { | |
[setupLock lock]; | |
setup = success; | |
[setupLock unlock]; | |
} | |
+ (void)xyz_clearSuccessful:(BOOL)success { | |
[setupLock lock]; | |
setup = success ? NO : setup; | |
[setupLock unlock]; | |
} | |
+ (BOOL)xyz_isSetupSuccessful { | |
return setup; | |
} | |
@end | |
// Modern queue based locking | |
#import "XYZManager+Additions.h" | |
@implementation XYZManager (Additions_new) | |
static BOOL setup = NO; | |
static dispatch_queue_t xyz_setupStateSetterQueue() { | |
static dispatch_queue_t setupQueue; | |
static dispatch_once_t onceToken; | |
dispatch_once(&onceToken, ^{ | |
setupQueue = dispatch_queue_create("com.xyz.setup.queue", DISPATCH_QUEUE_SERIAL ); | |
}); | |
return setupQueue; | |
} | |
+ (void)xyz_setupSuccessful:(BOOL)success { | |
dispatch_sync(xyz_setupStateSetterQueue(), ^{ | |
setup = success; | |
}); | |
} | |
+ (void)xyz_clearSuccessful:(BOOL)success { | |
dispatch_sync(xyz_setupStateSetterQueue(), ^{ | |
setup = success ? NO : setup;; | |
}); | |
} | |
+ (BOOL)xyz_isSetupSuccessful { | |
return setup; | |
} | |
@end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment