I’m not really sure what this is doing. Is dateFormatter only settable the first time?
static NSDateFormatter *dateFormatter = nil;
if (dateFormatter == nil) {
dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setTimeStyle:NSDateFormatterMediumStyle];
[dateFormatter setDateStyle:NSDateFormatterMediumStyle];
}
Normally I would read that to mean, set something to nil, then check if it’s nil, but if I NSLog within the condtional, it only gets called once?
Extra points if you can explain static in more depth, i know it creates a global variable (?), but thats about it.
No,
staticwill not makedateFormatterpart of the class. It might look like that, butstaticis not Objective-C’s feature and knows nothing about classes.staticis a standard C language’s feature. Remember that Objective-C is just an extension to C. Ifstaticis used within a method, it will create a global variable visible only from within that method.That means that this variable is not allocated on the stack but in the data segment. Variables locally defined in methods (non-static ones) are placed on the stack together with address of code where to return after method call is finished – therefore when execution leaves the method, local method’s variables are gone. Within this method,
dateFormatteralways represents the same place in memory.The point of making
dateFormatterstatic in this case is improving the performance – you always format dates with the same formatter, so it doesn’t make sense to recreate that formatter each time, therefore it is created and saved into a global variable only once.