I’m just getting started on Objective-C and I came across this example on creating a singleton:
+ (BNRItemStore *) sharedStore
{
static BNRItemStore *sharedStore = nil;
if (!sharedStore)
sharedStore = [[super allocWithZone:nil] init];
return sharedStore;
}
I understand what’s he’s trying to do – which is to return the same instance if it’s existing and create a new one if it’s not. What bothers me is this line:
static BNRItemStore *sharedStore = nil;
Won’t this line reset the sharedStore to a nil value everytime the method is called? I don’t see how the method will be able to return the previously existing instance if this line always sets it to nil.
Thanks in advance.
This is an element which Objective-C inherits from standard C. Any variable with static storage duration (which the
statictype specifier explicitly declares) is only initialized once, and the c standard says that this happens before the program starts.Note that it also mentions that if the variable with static storage duration is of ‘pointer type’, then it is automatically set to a NULL pointer (which is what nil is), so if you want, you can omit the
= nilpart of the declaration if you think it improves the readability of your function.