Skip to content

Instantly share code, notes, and snippets.

@grawert
Created September 17, 2017 13:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save grawert/1842357949f24878a16ca6922e1a5a7d to your computer and use it in GitHub Desktop.
Save grawert/1842357949f24878a16ca6922e1a5a7d to your computer and use it in GitHub Desktop.
Singleton Class in Objective-C
#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