Skip to content

Instantly share code, notes, and snippets.

@darkseed
Created August 18, 2012 09:32
Show Gist options
  • Save darkseed/3385633 to your computer and use it in GitHub Desktop.
Save darkseed/3385633 to your computer and use it in GitHub Desktop.
Objective C GCD singleton
+ (MyObject *)sharedInstance
{
static MyObject *instance;
static dispatch_once_t onceToken;
if (instance==nil) {
dispatch_once(&onceToken, ^{
instance = [[MyObject alloc] init];
});
}
return instance;
}
@itvexesme
Copy link

u can remove "if (instance==nil)", GCD launches block only once! no matter to check for nil.

this is valid GCD singleton code:

+ (id *) sharedObject
{
    static id * _sharedObject = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _sharedObject = [NSObject new];
    });
    return _sharedObject;
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment