0

I have downloaded a library off of github and have noticed that in the main singleton of the library there is a possible leak in this bit of code:

+(DDGameKitHelper*) sharedGameKitHelper
{
    @synchronized(self)
    {
        if (instanceOfGameKitHelper == nil)
        {
            [[DDGameKitHelper alloc] init];
        }

        return instanceOfGameKitHelper;
    }

    return nil;
}

Now obviously there is no release or autorelease anywhere so I must do it but how and in what way properly? I have looked at various Singleton design patterns on the Internet and they just assign, in this case, instanceOfGameKitHelper to the alloc and init line.

Anyway how would I properly fix this?

Thanks!

SimplyKiwi
  • 12,376
  • 22
  • 105
  • 191

2 Answers2

2

A singleton, by definition, is created once and never released. Think of it sort of like a global variable.

Take a look at this document from Apple: Cocoa Core Competencies - Singleton for more details.

Or for their example (at the bottom of the page): http://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/CocoaFundamentals/CocoaObjects/CocoaObjects.html#//apple_ref/doc/uid/TP40002974-CH4-SW32

I usually use @rmaddy's method though. Of course, even that way, you are still assigning the variable and never releasing it since it is still a singleton.

lnafziger
  • 25,760
  • 8
  • 60
  • 101
  • Is there any way to silence the warning then without silencing the others in my app? – SimplyKiwi Nov 20 '12 at 04:48
  • @iBradApps Yes, actually assign the allocated object to the `instanceOfGameKitHelper` variable. – rmaddy Nov 20 '12 at 04:49
  • Yeah, the code that you posted won't even work. Change `[[DDGameKitHelper alloc] init];` to `instanceOfGameKitHelper = [[DDGameKitHelper alloc] init];`. – lnafziger Nov 20 '12 at 04:52
  • If the author assigned the static variable inside of the init method, then it will work just fine. Of course, the more modern version is preferred these days :). – borrrden Nov 20 '12 at 06:06
2

A more modern way to setup singletons is like this:

+ (DDGameKitHelper *)sharedGameKitHelper {
    static DDGameKitHelper *instance = nil;
    static dispatch_once_t predicate;

    dispatch_once(&predicate, ^{ instance = [self new]; });

    return instance;
}
rmaddy
  • 314,917
  • 42
  • 532
  • 579