Question

In one of my third party libraries in my project, the singleton sharedInstance method seems to be throwing up an analyzer warning on the final return_sharedInstance line:

+ (BlockBackground*)sharedInstance
{
    if (_sharedInstance != nil) {
        return _sharedInstance;
    }

    @synchronized(self) {
        if (_sharedInstance == nil) {
            [[[self alloc] init] autorelease];
        }
    }

    return _sharedInstance;
}

Anyway, what is the proper way to actually fix this warning? Also I have seen that you are not supposed to do self alloc in a method like this, is that true?

Thanks!

Was it helpful?

Solution 2

It's the autorelease; you need to remove it, but more importantly (thanks @Yaman/@rmaddy) you aren't assigning the allocated object to _sharedInstance.

What will happen is that the next time the run loop ends, or the next time the autorelease pool is destroyed, whichever is sooner, the instance will be released. The _sharedInstance pointer will be left dangling and the next user of the object will fault with message sent to deallocated instance (or some such).

OTHER TIPS

Actually your line [[[self alloc] init] autorelease]; create on object and immediately throw it away. You need to replace with _sharedInstance = [[self alloc] init];

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top