Last active
December 25, 2015 00:59
-
-
Save mralexgray/6891945 to your computer and use it in GitHub Desktop.
Just to be complete, here's an implementation of Singleton which might be used from Interface Builder. The difference is in actualAlloc method. As [super alloc] would still call [self allocWithZone:] – it wouldn't allocate the object. "_alloc" IS THE KEY. Otherwise the object wouldn't be allocated From http://stackoverflow.com/a/13591502/547214
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
@interface IBSingleton : NSObject + (instancetype) shared; @end | |
@implementation IBSingleton | |
+ (instancetype) shared { __strong static id _sharedInstance = nil; static dispatch_once_t onlyOnce; | |
dispatch_once(&onlyOnce, ^{ _sharedInstance = [[self _alloc] _init]; }); return _sharedInstance; | |
} | |
+ (id) allocWithZone:(NSZone*)z { return [self shared]; } | |
+ (id) alloc { return [self shared]; } | |
- (id) init { return self; } | |
+ (id)_alloc { return [super allocWithZone:NULL]; } | |
- (id)_init { return [super init]; } | |
@end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment