madpoet
madpoet

Reputation: 1063

What's the point in setting a variable to nil first before instantiating it in Objective C

I've just started learning Objective C for iOS development. I'm trying to understand the following code:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    static NSString *CellIdentifier = @"BirdSightingCell";

    static NSDateFormatter *formatter = nil;
    if (formatter == nil) {
        formatter = [[NSDateFormatter alloc] init];
        [formatter setDateStyle:NSDateFormatterMediumStyle];
    }
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

    BirdSighting *sightingAtIndex = [self.dataController objectInListAtIndex:indexPath.row];
    [[cell textLabel] setText:sightingAtIndex.name];
    [[cell detailTextLabel] setText:[formatter stringFromDate:(NSDate *)sightingAtIndex.date]];
    return cell;
}

Question 1:

What does "static" do while declaring the variables CellIdentifier and formatter? It still works if I don't declare them static so what's the advantage of using static?

Q2:

static NSDateFormatter *formatter = nil;
if (formatter == nil) {

Isn't this expression always true? Why do we use that if statement there?

Upvotes: 2

Views: 80

Answers (2)

paxdiablo
paxdiablo

Reputation: 882028

The static means that the variable is set to nil once, at program startup, not every time you 'run' that statement, and that it maintains its value across multiple function calls.

Hence the first time you call that function, it will be nil and the if statement will fire. Subsequent calls to the function will have it set to a non-nil value so that the code in the if statement won't run again.

This is called lazy initialisation.

Upvotes: 2

DrummerB
DrummerB

Reputation: 40211

static in this context means, that it's a "shared" variable across multiple calls to this method. The first time it is called, the static variable will be nil. The next time it will be what ever it was set to during the last call.

Upvotes: 2

Related Questions