- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { // Date formatter for displaying dates static NSDateFormatter *dateFormatter = nil; if(dateFormatter == nil){ dateFormatter = [[NSDateFormatter alloc] init]; [dateFormatter setTimeStyle:NSDateFormatterMediumStyle]; [dateFormatter setDateFormat:NSDateFormatterMediumStyle]; }
Why do we initialize the dateFormatter variable and then immediately test for it being nil? Ive noticed this a lot in the newer Apple code. Curious!
-Buffalo
It’s because the variable is a local static variable, meaning that it maintains its value even after the local function returns or goes out of scope. So, the first time the function is executed, the variable is set to nil. Then, you check for nil and initialize the variable (this happens only once). Every other time the function is executed, the variable will have a non-nil value, so the initialization code block won’t be executed.