0

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

4 Answers 4

2

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

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

1

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.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.