Shinigami
Shinigami

Reputation: 2213

Singleton method stops code execution in iOS

I have a problem similar to this post, but that answer isn't working for me.

I have a singleton in my app which I used to create this way:

static POGalleryManager* defaultManager = nil;

+(POGalleryManager*)defaultManager
{
    if (!defaultManager) {
        defaultManager = [[super allocWithZone:NULL] init];
    }

    return defaultManager;
}

+(id)allocWithZone:(NSZone *)zone
{
    return [self defaultManager];
}

This was working fine, so I tried to get clever and use GCD for thread safety, switching to this, which is supposed to be better:

+(POGalleryManager*)defaultManager
{
    static POGalleryManager* __manager = nil;
    dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        __manager = [[POGalleryManager alloc] init];
    });

    return __manager;
}

The first time this gets called, everything is fine. The second time it gets called like this:

[[POGalleryManager defaultManager] someMethod];

someMethod never gets called. I tried stepping into that line with the debugger and once it got to the dispatch_once line it just continued execution (ie. it kicked me out of the debugger - so maybe the thread died?).

Any advice on this?

Upvotes: 2

Views: 162

Answers (1)

Bruno Koga
Bruno Koga

Reputation: 3874

Try to switch the

dispatch_once_t onceToken;

for

static dispatch_once_t onceToken;

Upvotes: 1

Related Questions