Created
September 17, 2017 13:15
-
-
Save grawert/1842357949f24878a16ca6922e1a5a7d to your computer and use it in GitHub Desktop.
Singleton Class 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
#import <Foundation/Foundation.h> | |
@interface SingletonClass : NSObject | |
@property (class, readonly) id sharedSingletonClass; | |
@end | |
@implementation SingletonClass | |
static SingletonClass *_sharedSingletonClass; | |
- (void)singletonInit { | |
// do initialisation here | |
} | |
+ (instancetype)allocWithZone:(struct _NSZone *)zone { | |
return [SingletonClass sharedSingletonClass]; | |
} | |
+ (instancetype)sharedSingletonClass { | |
static dispatch_once_t onceToken; | |
dispatch_once(&onceToken, | |
^{ | |
_sharedSingletonClass = [[super allocWithZone:nil] init]; | |
if(_sharedSingletonClass) | |
[_sharedSingletonClass singletonInit]; | |
}); | |
return _sharedSingletonClass; | |
} | |
@end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment