Why does the initial nil assignment happen only 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 in the "Learn Cocoa on mac" section. Does the book indicate that the initial assignment to nilse occurs only when the method is first called? My question is how / why is this so?

+3
source share
1 answer

Because static is only initialized once. Despite the fact that the variable is inside the function, its storage time makes up the entire program. It is initialized once and retains its value between function calls.

This code you posted is exactly the same conceptual as:

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

( motivations). , , , , .

ISO C99 (, , C, ):

( ).

+6

Source: https://habr.com/ru/post/1773786/


All Articles