开发者

Static variable scope within class?

开发者 https://www.devze.com 2022-12-22 07:32 出处:网络
Can anyone tell me what the scope of the static variable in the class below is? @implementation SharedManager

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开发者_JS百科 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


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.


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++.

0

精彩评论

暂无评论...
验证码 换一张
取 消