0

I am seeing everywhere that people initialise singletons like this in obj-c:

+ (instancetype)sharedInstance {
    static dispatch_once_t once;
    static id sharedInstance;

    dispatch_once(&once, ^{
        sharedInstance = [self new];
    });    
    return sharedInstance;
}

What happened to the plain old following?

+ (instancetype)sharedInstance {
    static id sharedInstance;

    if (!sharedInstance) {
        sharedInstance = [self new];
    }
    return sharedInstance;
}

Is there a significant benefit to the first method over the second one?

Chirag Arora
  • 877
  • 1
  • 9
  • 22

0 Answers0