Last active
October 1, 2015 15:38
-
-
Save tudormunteanu/2017482 to your computer and use it in GitHub Desktop.
Obj-c singleton
This file contains hidden or 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
| // | |
| // 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