Skip to content

Instantly share code, notes, and snippets.

@nicklockwood
Last active December 11, 2019 15:17
Show Gist options
  • Save nicklockwood/9605636 to your computer and use it in GitHub Desktop.
Save nicklockwood/9605636 to your computer and use it in GitHub Desktop.
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