Reputation: 22715
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.
Upvotes: 1
Views: 261
Reputation: 18290
This is an element which Objective-C inherits from standard C. Any variable with static storage duration (which the static
type specifier explicitly declares) is only initialized once, and the c standard says that this happens before the program starts.
6.2.4 3) An object whose identifier is declared with external or internal linkage, or with the storage-class specifier static has static storage duration. Its lifetime is the entire execution of the program and its stored value is initialized only once, prior to program startup.
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 = nil
part of the declaration if you think it improves the readability of your function.
Upvotes: 4
Reputation: 104698
Won't this line reset the sharedStore to a nil value everytime the method is called?
Because sharedStore
is static
, it will be initialized (the = nil
bit) the first time it is called. Subsequent calls will skip these instructions.
I don't see how the method will be able to return the previously existing instance if this line always sets it to nil.
Because it is static
the variable and its value will remain in memory after the method exits.
Basically, you can think of this as a global variable, but it is accessible only to +sharedStore
.
Upvotes: 1