ios - Override init method to have singleton instance -
one third party library uses class initialisation:
classa *a = [[myclass alloc] init]];
i need myclass
shared instance (aka singleton) can't modify 3rd party way of executing myclass
initialization
i trying override init
method following:
- (instancetype)init { return [[self class] sharedinstance]; } + (loopmenativeevent *)sharedinstance { static loopmenativeevent *_sharedinstance = nil; static dispatch_once_t oncetoken; dispatch_once(&oncetoken, ^{ _sharedinstance = [loopmenativeevent new]; }); return _sharedinstance; }
but, unfortunately new
causes alloc init
executed.
simplest way know have 2 separate classes:
myclass
initialised throughalloc init
- separate
mysharedclass
singleton
is there possibility achieve having 1 class?
how inheritance,
create new class named childclass inherit myclass , add following 2 methods
+ (instancetype)sharedinstance { static childclass *sharedinstance = nil; static dispatch_once_t oncetoken; dispatch_once(&oncetoken, ^{ sharedinstance = [[childclass alloc] init]; }); return sharedinstance; } - (id)init { self = [super init]; return self; }
Comments
Post a Comment