codecowboy
codecowboy

Reputation: 10095

Why does initial assignment to nil only happen once for a local static variable in a class method?

+ (NSArray *)motivations {
static NSArray *motivations = nil;
if (!motivations) {
    motivations = [[NSArray alloc] initWithObjects:@"Greed", @"Revenge", @"Bloodlust", @"Nihilism", @"Insanity", nil];
}
return motivations;

}

The above code is from 'Learn Cocoa on the mac'. The book states that the initial assignment to nil only occurs the first time the method is called? My question is how/why is that the case?

Upvotes: 3

Views: 237

Answers (1)

paxdiablo
paxdiablo

Reputation: 882028

Because statics are initialised only once. Despite the fact that the variable is inside the function, it's storage duration is that of the entire program. It's initialised once and maintains its value in between invocations of the function.

That code you posted is exactly the same conceptually as:

NSArray *motivations = nil;
+ (NSArray *)motivations {
    if (!motivations) {
        motivations = [[NSArray alloc] initWithObjects:@"Greed", @"Revenge",
            @"Bloodlust", @"Nihilism", @"Insanity", nil];
    }
    return motivations;
}

in terms of the storage duration (though not the scope since motivations is now visible from outside). What you have here is a kind of singleton pattern which initialises the array to nothing, then populates it once the first time you use this code.

The ISO C99 standard (yes, I do realise this isn't C but the concepts are the same) states:

All objects with static storage duration shall be initialized (set to their initial values) before program startup.

Upvotes: 6

Related Questions