Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why should you check a static variable for nil if it was initialized to nil on the previous line?

Below is a code sample from Apple's iOS Core Data tutorial and I thought it was weird that the conditional statements are checking if the object is nil. Wouldn't the object always evaluate to nil if the line before the conditional sets the object to nil?

// A date formatter for the time stamp
static NSDateFormatter *dateFormatter = nil;
if (dateFormatter == nil) {
    dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setTimeStyle:NSDateFormatterMediumStyle];
    [dateFormatter setDateStyle:NSDateFormatterMediumStyle];
}
like image 992
Kyle Hayes Avatar asked Jan 07 '12 20:01

Kyle Hayes


3 Answers

Because of the static. This variable is not set to nil whenever the execution passes through that statement, it 's only set on program startup.

That's a feature of static storage duration variables. They're set to their initialised value at startup and retain whatever value you set them to after that. For example, the following code:

void plugh(void) {
    static int xyzzy = 0;
    printf (" %d", xyzzy); // or Obj-C equivalent.
    xyzzy++;
}

will not output a long string of zeros if you call it a hundered times. It will output:

0 1 2 3 4 ...

In th case of the Apple code, it means the date formatter will be created on demand and (unless you set it back to nil somewhere else) only once. This can someties be important for performance if the object creation is a non trivial thing but, even if not, there's no point in continuously recreating something you can simply re-use.

like image 165
paxdiablo Avatar answered Sep 28 '22 10:09

paxdiablo


I'm assuming this code is from the body of a function. You need to note that the variable is static. That means yes, the first time this function is called, it will be set to nil. However, the next time the function is called, it retains its value from the previous call.

So the result of this is lazy initialization. A new NSDateFormatter is initialized only the first time this function is called.

static essentially makes it a global variable, initialized to that value, but is visible only to the function it is declared in.

like image 40
Jonathon Reinhart Avatar answered Sep 28 '22 12:09

Jonathon Reinhart


The "static" means it only evaluated once, upon initializing that class and on the first run through. Subsequent runs through will skip right over it and continue to the next line.

like image 27
Hubert Kunnemeyer Avatar answered Sep 28 '22 11:09

Hubert Kunnemeyer