ios - Issues with singleton -
i have created single ton arc,
+ (myclass *)sharedinstance { static myclass *sharedspeaker = nil; static dispatch_once_t oncetoken; dispatch_once(&oncetoken, ^{ sharedspeaker = [[self alloc] init]; }); return sharedspeaker; } - (id)init { if (self = [super init]) { } return self; }
but here creating instances this:
id speaker3 = [[myclass alloc] init]; id speaker = [myclass sharedinstance]; id speaker2 = [[myclass alloc] init]; nslog(@"speaker 1= %@ \n speaker 2 = %@\n speaker3 = %@",speaker,speaker2,speaker3);`
i got output as:
speaker 1= <myclass : 0xa45f5e0> speaker 2 = <myclass : 0xa461740> speaker3 = <myclass : 0xa4529e0>
this looking desired behaviour. how stop when giving singleton in library user. need block him creating new instance. need make static global if make global cant create global variable of same name there conflict right. memebers can give solution on this?
for example using assert in init
method.
- (id)init { static int maxinstances = 1; assert(maxinstances > 0); maxinstances--; ... }
Comments
Post a Comment