Suppose if I want to implement both getter and setter I will do like this -
@interface Person () {
dispatch_queue_t _myConcurrentQueue;
}
@property (nonatomic, copy) NSString *personName;
@end
@implementation Person
- (instancetype)init
{
if (self = [super init])
{
_myConcurrentQueue = dispatch_queue_create(NULL, DISPATCH_QUEUE_CONCURRENT);
}
return self;
}
@synthesize personName = _personName;
- (NSString *)personName {
__block NSString *tmp;
dispatch_sync(_myConcurrentQueue, ^{
tmp = _personName;
});
return tmp;
}
- (void)setpersonName:(NSString *)personName {
NSString* tmp = [personName copy];
dispatch_barrier_async(_myConcurrentQueue, ^{
_personName = tmp;
});
}
@end
But if I want to initialize my property lazily, then how can I make it thread safe? Example -
- (NSString *)personName {
If (!_personName) {
_personName = "Some Name"
}
return _personName;
}
What should I use serial queue with dispatch_async or concurrent queue with dispatch_async barrier and why?