Question

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!

Was it helpful?

Solution

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;
}

OTHER TIPS

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.

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