4 ms·
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 clutter
by fphilipe 14y 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?
- eliperkins 14y agoShould 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.