Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using dispatch_once

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?

like image 411
Kermit the Frog Avatar asked Dec 20 '22 22:12

Kermit the Frog


2 Answers

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.

like image 190
Brad Allred Avatar answered Jan 01 '23 20:01

Brad Allred


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.

like image 22
Jano Avatar answered Jan 01 '23 18:01

Jano