-
-
Save eiffelqiu/979981 to your computer and use it in GitHub Desktop.
Singletons in Objective C
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// A normal singleton | |
static AppInfo * sharedAppInfo = nil; | |
+ (AppInfo *) sharedAppInfo | |
{ | |
if ( sharedAppInfo == nil ) | |
{ | |
[[self alloc] init]; | |
} | |
return sharedAppInfo; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// A more thread safe singleton | |
static AppInfo * sharedAppInfo = nil; | |
+(AppInfo *) sharedAppInfo | |
{ | |
@synchronized(self) | |
{ | |
if ( sharedAppInfo == nil ) | |
{ | |
[[self alloc] init]; | |
} | |
} | |
return sharedAppInfo; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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