Izac
Izac

Reputation: 71

Issues with Singleton in objective C

I am trying to implement a singleton, it is acting as a stub DAO and I need different areas of the application to be able to read and write to it. The first class that uses it can do so without any issue using my sharedSingleton class level constructor, however when I attempt to access this from another class in the exact same way I get a EXC_BAD_ACCESS error and the debug line in the 1st line of the method I am calling on the singleton is 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 the exact same call twice both in viewDidLoad

    DAOController *daoController = [DAOController sharedSingleton];
self.teams = [daoController getTeamsForPlayer];

But in the 2nd it throws an exception or a EXC_BAD_ACCESS

2011-04-28 18:31:22.403 IScore[5637:207] -[NSKeyValueIvarSetter getTeamsForPlayer]: unrecognized selector sent to instance 0xa707220 2011-04-28 18:31:22.435 IScore[5637:207] * Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[NSKeyValueIvarSetter getTeamsForPlayer]: unrecognized selector sent to instance 0xa707220' Call stack at first throw:

The method simply 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 I change the 2nd instance to non shared I can run the method without issue

    DAOController *daoController = [[DAOController alloc]init];

Any assistance would be appreciated. Singleton pattern was taken from last entry on What should my Objective-C singleton look like?

Upvotes: 2

Views: 628

Answers (1)

Vincent Guerci
Vincent Guerci

Reputation: 14419

Looks like your singleton has been deallocated and that another instance took its address.

You should check your code to find how this is possible. (you should never retain / release that singleton)

That's why I strongly suggest using Matt Gallagher's cocoawithlove singleton macro that you can download there, which is super easy and concise to use :

SYNTHESIZE_SINGLETON_FOR_CLASS(MyClassName);

It is a perfect singleton implementation, that avoid such issues by deallocating accidently your singleton, which looks like to be your problem. It is based on Apple recommandations, which overrides release, retainCount and such to protect your singleton.

Upvotes: 3

Related Questions