Peter Lapisu
Peter Lapisu

Reputation: 20985

Setting static inside its method call (with singleton pattern)

is smth. like this legit? it compiles and looks running ok, but is it ok? (aim setting myself to nil, inside my method)

i mean iam setting myself static to nil, in a method

static MyClass * StaticInstance = nil;

+ (MyClass *) sharedStaticInstance 
{
    if (StaticInstance == nil) {
        StaticInstance = [[MyClass alloc] init];
    }

    return StaticInstance;
}

- (void) killStaticSelf
{
    StaticInstance = nil;
}

and later

[[MyClass sharedStaticInstance] doSmth]; // our static instance is created
[[MyClass sharedStaticInstance] killStaticSelf]; // now its killed inside itself method
[[MyClass sharedStaticInstance] doSmth]; // now it should recreate again

Upvotes: 0

Views: 73

Answers (4)

AndersK
AndersK

Reputation: 36082

your sharedInstance method is not thread safe so you could get a race condition in this code:

if (StaticInstance == nil) {
    StaticInstance = [[MyClass alloc] init];
}

- (void) killStaticSelf
{
    StaticInstance = nil;
}

the above code has a leak since you do not provide StaticInstance as a retain property (apparently). You could instead wrap your singleton code in a property but that uses the same static instance.

Upvotes: 1

Aram Kocharyan
Aram Kocharyan

Reputation: 20431

Yes, that's how it's done. I use the sharedStaticInstance often, though I don't usually create a destructor it's probably a good idea, as long as all references to the shared instance in this class pass through sharedStaticInstance first.

EDIT: I just noticed that killStaticSelf is an instance method - it should be a class method I believe, but there shouldn't be any issue either way.

[MyClass killStaticSelf];

Even as the function stack closes, since sending messages to nil doesn't cause issues in Objective-C.

Upvotes: 1

Apurv
Apurv

Reputation: 17186

Its having a memory leak. You should dealloc the StaticInstance first and then you should assign nil to it.

Upvotes: 2

Eugene
Eugene

Reputation: 10045

It's legit, but you need to release the variable before setting it to nil, to avoid memory leaks if you're not using ARC.

Though comprehension of such singleton usage logic is beyond my humble brain abilities.

Upvotes: 0

Related Questions