Skip to content

Instantly share code, notes, and snippets.

@darkseed
Created May 11, 2011 22:21
Show Gist options
  • Save darkseed/967518 to your computer and use it in GitHub Desktop.
Save darkseed/967518 to your computer and use it in GitHub Desktop.
Singletons in Objective C
// A normal singleton
static AppInfo * sharedAppInfo = nil;
+ (AppInfo *) sharedAppInfo
{
if ( sharedAppInfo == nil )
{
[[self alloc] init];
}
return sharedAppInfo;
}
// A more thread safe singleton
static AppInfo * sharedAppInfo = nil;
+(AppInfo *) sharedAppInfo
{
@synchronized(self)
{
if ( sharedAppInfo == nil )
{
[[self alloc] init];
}
}
return sharedAppInfo;
}
// A slightly slower one but just as thread safe
static dispatch_once_t pred;
static AppInfo * sharedAppInfo = nil;
+(AppInfo *) sharedAppInfo
{
// more efficient way .
dispatch_once (&pred , ^{
sharedAppInfo = [[self alloc] init];
});
return sharedAppInfo;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment