Skip to content

Instantly share code, notes, and snippets.

@nicklockwood nicklockwood/gist:9605636
Last active Dec 25, 2017

Embed
What would you like to do?
Singleton Category implementation
Singleton.h
-------------
@protocol Singleton
@optional
+ (instancetype)sharedInstance;
@end
Singleton.m
-------------
#import "Singleton.h"
#import <objc/runtime.h>
@implementation NSObject (singleton)
+ (instancetype)sharedInstance
{
if (![self conformsToProtocol:@protocol(Singleton)])
{
[self doesNotRecognizeSelector:_cmd];
}
@synchronized (self)
{
id instance = objc_getAssociatedObject(self, _cmd);
if (!instance)
{
instance = [[self alloc] init];
objc_setAssociatedObject(self, _cmd, instance, OBJC_ASSOCIATION_RETAIN);
}
return instance;
}
}
@end
Usage
-------
#import "Singleton.h"
@interface MyObject : NSObject <Singleton>
@end
// you can now safely access shared instance of MyObject
// by using the +sharedInstance method
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.