I have the following code:
static NSDictionary * errorDescriptions = nil;
+ (NSString *) errorsFromCode: (WPErrorCode) code {
if(errorDescriptions == nil) {
errorDescriptions = @{[NSNumber numberWithInt: InvalidCar]: NSLocalizedStringFromTable(@"Car is invalid.", @"WePay", @"validation: invalid car"), ...
}
return [errorDescriptions objectForKey: [NSNumber numberWithInt: code]];
}
I got advice to change the code above to:
+ (NSString *) errorsFromCode: (WPErrorCode) code {
static NSDictionary * errorDescriptions = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
errorDescriptions = @{[NSNumber numberWithInt: InvalidCar]: NSLocalizedStringFromTable(@"Car is invalid.", @"WePay", @"validation: invalid car"), ...
}
return [errorDescriptions objectForKey: [NSNumber numberWithInt: code]];
}
Why is that the case? Why do I have to use dispatch_once?
You don't have to use it, but what you put in the block will only be executed once in a thread-safe manner.
You don't need, and shouldn't have, the if errorDescriptions == nil
check if you will be using dispatch_once
.
dispatch_once is used to create objects whose initialization is expensive, or to block other threads while the object is being initialized. None of these situations apply here. It doesn't matter how many times you initialize that object, and it's not expensive as to require special treatment. It looks pointless to me. Brad is right to say the if in the second block is superfluous.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With