Last active
August 29, 2015 14:04
-
-
Save situee/305c1ec6719108682dc2 to your computer and use it in GitHub Desktop.
objective-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
| // GCD using "instancetype" as return type | |
| + (instancetype)shared | |
| { | |
| static id shared; | |
| static dispatch_once_t token; | |
| dispatch_once(&token, ^{ | |
| shared = [[self alloc] init]; | |
| }); | |
| return shared; | |
| } | |
| // The following two methods are from http://www.galloway.me.uk/tutorials/singleton-classes/ | |
| // use GCD | |
| + (id)sharedManager { | |
| static MyManager *sharedMyManager = nil; | |
| static dispatch_once_t onceToken; | |
| dispatch_once(&onceToken, ^{ | |
| sharedMyManager = [[self alloc] init]; | |
| }); | |
| return sharedMyManager; | |
| } | |
| // use "synchronized" | |
| + (id)sharedManager { | |
| static MyManager *sharedMyManager = nil; | |
| @synchronized(self) { | |
| if (sharedMyManager == nil) | |
| sharedMyManager = [[self alloc] init]; | |
| } | |
| return sharedMyManager; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment