Kyle Hayes
Kyle Hayes

Reputation: 5302

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];
}

Upvotes: 8

Views: 2226

Answers (3)

paxdiablo
paxdiablo

Reputation: 882028

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.

Upvotes: 19

Jonathon Reinhart
Jonathon Reinhart

Reputation: 137467

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.

Upvotes: 5

Hubert Kunnemeyer
Hubert Kunnemeyer

Reputation: 2261

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.

Upvotes: 1

Related Questions