cfischer
cfischer

Reputation: 24902

Singletons and memory management in Cocoa

I have a singleton as class method:

+(WordsModel *) defaultModel{
    static WordsModel *model = nil;  

    if (!model) {
        model =  [[[self alloc] init] autorelease];
    }

    return model;
}

What happens with the static reference to model inside the method? Will it ever get released?

Upvotes: 0

Views: 125

Answers (2)

Sherm Pendley
Sherm Pendley

Reputation: 13612

Not only will it get released (because you sent it an -autorelease message), your next attempt to use it will probably lead to a crash because the model pointer wasn't set to nil when the object was released. So, it will then point to memory that's either garbage, or (if that memory has been re-used) to a different object than the one you expected.

Upvotes: 3

Macmade
Macmade

Reputation: 53960

It won't work as you are autoreleasing your instance of your class...

On the next runloop, it will be released...

Take a look at the standard singleton patterns: http://www.cocoadev.com/index.pl?SingletonDesignPattern

The static instance should be a global variable, that will be freed when your app exits...

Upvotes: 1

Related Questions