Skip to content

Instantly share code, notes, and snippets.

@tudormunteanu
Last active October 1, 2015 15:38
Show Gist options
  • Select an option

  • Save tudormunteanu/2017482 to your computer and use it in GitHub Desktop.

Select an option

Save tudormunteanu/2017482 to your computer and use it in GitHub Desktop.
Obj-c singleton
//
// Non-thread safe
//
@interface MySingleton : NSObject
{
}
+ (MySingleton *)sharedSingleton;
@end
@implementation MySingleton
+ (MySingleton *)sharedSingleton
{
static MySingleton *sharedSingleton;
@synchronized(self)
{
if (!sharedSingleton)
sharedSingleton = [[MySingleton alloc] init];
return sharedSingleton;
}
}
@end
//
// Thread safe
//
+(MyClass *)sharedInstance
{
static MyClass *sharedInstance = nil;
static dispatch_once_t pred;
dispatch_once(&pred, ^{
sharedInstance = [[MyClass alloc] init];
});
return sharedInstance;
}
//
// Macro. Thread safe.
//
/*!
* @function Singleton GCD Macro
*/
#ifndef SINGLETON_GCD
#define SINGLETON_GCD(classname) \
\
+ (classname *)shared##classname { \
\
static dispatch_once_t pred; \
static classname * shared##classname = nil; \
dispatch_once( &pred, ^{ \
shared##classname = [[self alloc] init]; \
}); \
return shared##classname; \
}
#endif
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment