Trouble understanding static class in iOS

廉价感情. 提交于 2020-01-25 04:59:06

问题


I am following the Big Nerd Ranch book on iOS programming.

There is a sample of a static class:

#import <Foundation/Foundation.h>

@interface BNRItemStore : NSObject

+ (BNRItemStore *) sharedStore;

@end

I have a problem undrstanding the bit below with question mark in the comments. If I try to alloc this class, the overriden method will bring me to sharedStore, which in turn sets the static pointer sharedStore to nil. The conditional after will hit the first time because the pointer doesn't exist.

The idea is that the second time I am in the same place, it would not alloc a new instance and get the existing instance instead. However with static BNRItemStore *sharedStore = nil; I am setting the pointer to nil and destroy it, isn't it? Hence every time I am creating unintentionally a new instance, no?

#import "BNRItemStore.h"

@implementation BNRItemStore

+ (BNRItemStore*) sharedStore
{
    static BNRItemStore *sharedStore = nil; // ???
    if (!sharedStore) {
        sharedStore = [[super allocWithZone:nil] init];
    }
    return sharedStore;
}

+(id)allocWithZone:(NSZone *)zone
{
    return [self sharedStore];
}

@end 

回答1:


However with static BNRItemStore *sharedStore = nil; I am setting the pointer to nil and destroy it, isn't it?

No, you do not set it to nil: the expression in the static initializer is computed only once; the second time around the initialization has no effect. This looks very confusing, but this is the way the function-static facility works in C (and by extension, in Objective-C).

Try this as an example:

int next() {
    static int current = 123;
    return current++;
}

int main(int argc, char *argv[]) {
    for (int i = 0 ; i != 10 ; i++) {
        NSLog(@"%d", next());
    }
    return 0;
}

This would produce a sequence of increasing numbers starting at 123, even though the code makes it appear as if current is assigned 123 every time that you go through the function.



来源:https://stackoverflow.com/questions/18724522/trouble-understanding-static-class-in-ios

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!