tags:

views:

117

answers:

3
    - (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

+2  A: 

Most likely becuase it's a static variable. In other words, its value shouldn't change after the method exits. Most likely, this is because you only want one instance of the variable that persists with each method call.

htw
+5  A: 

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.

Jason Coco
Ah, ok. So this is similar to the Singleton design pattern. Neato ;)
Buffalo
It's quite a bit different, actually. It is used a lot in C where functions need to keep some kind of state data but where it doesn't make sense for anything but the function to know or care about what that data is.
Jason Coco
+1  A: 

The variable is a local static variable. It's value is maintained between method invocations. Thus, on the first call, it is initialized to nil and then its value is reassigned to the address of an instance of NSDateFormatter*. On subsequent calls, the value is non-nil (because it has been assigned to the address of the NSDateFormatter instance) and so it is not reinitialized.

A local static variable is like a namespace-scoped global variable. It's value is global to the process, but it is visible only within the scope where it was declared.

Barry Wark