1

The following code is present in Apple's iOS development guides (found here):

- (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;
}

Why set formatter equal to nil then check if it's nil? In which case would it not be?

4

3 回答 3

3

formatter is a static variable, which is only initialized once.. So

static NSDateFormatter *formatter = nil;

will be executed only once for multiple execution of this function.

In short, they are making sure to reuse the formatter object, instead of creating it every time.

So Regarding your question,

In which case would it not be?

the formatter object will be nil only for the first execution of the function, so the code

 formatter = [[NSDateFormatter alloc];
 [formatter setDateStyle:NSDateFormatterMediumStyle];

will be only executed once.

For a change the wikipedia page on static variable is easy to read, and help you understand the concept. They use a C programming language example, but the concept is similiar in objective C.

于 2012-12-27T03:45:39.253 回答
1

It's because it's static. So, the first time cellForRowAtIndexPath is called, the formatter will indeed be nil and will therefore be initialized as a valid NSDateFormatter with a dateStyle of NSDateFormatterMediumStyle. The next time this method is called, formatter will no longer be nil, and you won't need to initialize it again. It's just a convenient (albeit, apparently confusing if you're not familiar with the static qualifier) way of having a variable that is initialized only once.

于 2012-12-27T03:49:29.380 回答
1

formatter is static, so that it will only be initialized for one time only. Thus, it may not be nil in the next time this function is called.

see here: http://mobiledevelopertips.com/objective-c/java-developers-guide-to-static-variables-in-objective-c.html

于 2012-12-27T03:51:07.260 回答