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 tonilwhenever 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:
will not output a long string of zeros if you call it a hundered times. It will output:
In th case of the Apple code, it means the date formatter will be created on demand and (unless you set it back to
nilsomewhere 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.