Skip to content

Instantly share code, notes, and snippets.

@mralexgray
Last active December 25, 2015 00:59
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 mralexgray/6891945 to your computer and use it in GitHub Desktop.
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
@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