0

Can anyone tell me what the scope of the static variable in the class below is?

@implementation SharedManager

static id myInstance = nil;

+(id)sharedInstance {
    if(myInstance == nil) {
        myInstance = [[self alloc] init];
    }
    return myInstance;
}

In a test I created an instance from the class and then released it, but noticed that on creating a second instance that the static was not nil (i.e. pointing to the previously released object) For the test I fixed this by overriding -(void)dealloc for the class.

-(void)dealloc {
    NSLog(@”_deal: %@”, [self class]);
    [super release]
    myInstance = nil
}

gary

2 Answers 2

1

The scope of the variable is limited to the "SharedManager" class itself (since it's declared in the @implementation section, it will not be visible to subclasses).

The duration of the variable is "static" meaning that there's one copy of the variable associated with the class itself; it does not get created/destroyed when you alloc/dealloc instances of the class.

Also; if your class is intended to be thread-safe, you should do

@synchronized(self) {
if (myInstance == nil) {
    myInstance = [[self alloc] init];
}

to your sharedInstance method, to handle the case of two threads simultaneously calling sharedInstance.

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

2 Comments

Thank you David, yes I appreciate that, but in this case the singleton is simply for the model data, its a simple MVC iPhone application and I don't foresee and threading happening. I just wanted to make sure how it was working, hence the unneeded dealloc as I don't see it being released either
Just a quick note from my singleton travels, @synchronized([SharedManager class]) { might work better, or so I have been led to believe.
0

As far as I understand, the visibility scope of that variable is below its declaration within the current source file, and the lifetime is global. As if it's a C static variable.

In other news, you can write C functions within the @implementation block - they'll work like regular C functions.

There's no notion of "class static" variables in ObjC, AFAIK. This is not C++.

2 Comments

Thank you, not sure about the "C Function" bit, the code shows "Objective-C Class Methods" ... but I could always be missing your point.
Because Objective-C is C with O-O extensions, you can always do plain old C stuff, plus you can mix and match. What Seva is talking about is writing plain old C functions that contain Objective-C code. (Take a look at Apple's Foundation Functions reference for some examples.) As Seva points out, those can be placed anywhere in a .m file.

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.