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];
}
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With