iphone - Issues with Singleton in objective C -


i trying implement singleton, acting stub dao , need different areas of application able read , write it. first class uses can without issue using sharedsingleton class level constructor, when attempt access class in exact same way exc_bad_access error , debug line in 1st line of method calling on singleton never hit.

+(daocontroller *) sharedsingleton {         static daocontroller *sharedsingleton;      @synchronized(self)     {         if (!sharedsingleton)             sharedsingleton = [[daocontroller alloc] init];          return sharedsingleton;     } }      -(id) init {     if (self = [super init])     {         [self initdictionary];     }     return self; } 

i make exact same call twice both in viewdidload

    daocontroller *daocontroller = [daocontroller sharedsingleton]; self.teams = [daocontroller getteamsforplayer]; 

but in 2nd throws exception or exc_bad_access

2011-04-28 18:31:22.403 iscore[5637:207] -[nskeyvalueivarsetter getteamsforplayer]: unrecognized selector sent instance 0xa707220 2011-04-28 18:31:22.435 iscore[5637:207] * terminating app due uncaught exception 'nsinvalidargumentexception', reason: '-[nskeyvalueivarsetter getteamsforplayer]: unrecognized selector sent instance 0xa707220' call stack @ first throw:

the method does

   -(nsmutablearray*) getteamsforplayer {     nsmutablearray *teamsforplayer = [[[nsmutablearray alloc] init] autorelease];     team *team1 = [self.teams objectforkey:[nsnumber numberwithint:1]];     [teamsforplayer addobject:team1];     [team1 release];     return teamsforplayer; } 

if change 2nd instance non shared can run method without issue

    daocontroller *daocontroller = [[daocontroller alloc]init]; 

any assistance appreciated. singleton pattern taken last entry on what should objective-c singleton like?

looks singleton has been deallocated , instance took address.

you should check code find how possible. (you should never retain / release singleton)

that's why suggest using matt gallagher's cocoawithlove singleton macro can download there, super easy , concise use :

synthesize_singleton_for_class(myclassname); 

it perfect singleton implementation, avoid such issues deallocating accidently singleton, looks problem. based on apple recommandations, overrides release, retaincount , such protect singleton.


Comments