Trouble understanding static class in iOS

2019-07-22 17: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.



标签: ios static