Search code examples
iosobjective-cdispatch

Is there any benefits at all to use dispatch_once pattern with primitives?


Which is better?

static unsigned unitFlags;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
    unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit;
});

OR is that just as efficient as writing

unsigned unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit;

Or is there some other patterns more efficient? Would a define be better for 'unitFlags'?


Solution

  • You should just do:

    static unsigned unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit;
    

    You only need to do the dispatch_once trick if the expression on the right isn't a valid compile-time constant. But this is a valid compile-time constant, so you don't have to go through that slight of hand.

    But the static expression is generally better than a #define (it's typed, and for some complicated expressions, it can be more efficient). Stick with the static, in my opinion.