Hacker News new | ask | show | jobs
by fphilipe 4901 days ago
Can someone explain to me why I should use dispatch_once at all when a simple check whether the static variable is nil would suffice? It always seems so cluttered.

Compare this:

  + (MyClass *)sharedClass {
      static MyClass *_shared = nil;
      static dispatch_once_t onceToken;
      dispatch_once(&onceToken, ^{
          _shared = [[MyClass alloc] init];
      });
      return _shared;
  }
...to this:

  + (MyClass *)sharedClass {
      static MyClass *_shared = nil;
      if (!_shared)
          _shared = [[MyClass alloc] init];
      return _shared;
  }
Is there any difference regarding performance?
1 comments

Should you call the singleton on multiple threads, there is a chance you could get inconsistent results based on a race condition. Using GCD ensures that the singleton is truly only created once.