Skip to content

Instantly share code, notes, and snippets.

@jeksys
Created July 12, 2011 13:11
Show Gist options
  • Save jeksys/1077945 to your computer and use it in GitHub Desktop.
Save jeksys/1077945 to your computer and use it in GitHub Desktop.
Singleton Objects - Lazy ini
Singleton Objects
Lazy initialization is common
@implementation FooController
// #1
+ (FooController *)sharedInstance
{
static dispatch_once_t once;
static FooController *instance;
dispatch_once(&once, ^{
instance = [[FooController alloc] init];
return instance;
} @end
// #2
+ (FooController *)sharedInstance
{
static FooController *instance;
if (!instance)
instance = [[FooController alloc] init];
return instance;
}
@end
// #3
+ (FooController *)sharedInstance; // will create
+ (FooController *)activeInstance; // won’t create
+ (FooController *)sharedInstance
createIfNeeded:(BOOL)createIfNeeded;
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment