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!
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
_sharedInstancepointer will be left dangling and the next user of the object will fault with message sent to deallocated instance (or some such).