+(instancetype) objectWithAttribute:(NSString *)attribute {
__block id newInstance;
dispatch_semaphore_t s = dispatch_semaphore_create(0);
dispatch_async(dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(void){
newInstance = [[Object alloc] initWithAttribute:attribute];
dispatch_semaphore_signal(s);
});
dispatch_semaphore_wait(s, DISPATCH_TIME_FOREVER);
return newInstance;
}
So I came across this block of code. I have a very limited understanding of semaphores and concurrency in general. But to me, this code:
- Sets a semaphore token.
- dispatch_async a block that initialises an object.
- signals once the object has been created that the new instance can be returned.
I reached this conclusion from reading the marked answer here: Intangible Order of Execution (dispatch_semaphore_t, dispatch_group_async) and the Use of Them in Combination with Different Dispatch Queue Types
If you follow through into the init and the logic there, there's nothing that goes outside normal flow or onto a new thread or anything. My question is this, why can't I replace the above method with:
+(instancetype) objectWithAttribute:(NSString *)attribute {
id newInstance = [[Object alloc] initWithAttribute:attribute];
return newInstance;
}
Thanks