2012-12-27 44 views
1

下面的代碼存在於蘋果的iOS開發指南(發現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; 
} 

爲什麼一套格式化等於零,然後檢查它是否爲零?在哪種情況下不會?

回答

3

formatter靜態變量,它僅初始化一次。所以

static NSDateFormatter *formatter = nil; 

將用於該功能的多個執行只執行一次。

總之,他們確保重複使用對象,而不是每次創建它。

所以,關於你的問題,

在這種情況下,豈不是?

格式化對象將nil只對功能的第一次執行,所以代碼

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

將僅執行一次。

對於更改wikipedia page上的靜態變量很容易閱讀,並幫助您理解概念。他們使用C編程語言的例子,但這個概念與目標C相似。

1

這是因爲它是static。因此,第一次調用cellForRowAtIndexPath時,formatter確實將爲nil,因此將被初始化爲有效的NSDateFormatter,其中dateStyle的值爲NSDateFormatterMediumStyle。下次調用此方法時,formatter將不再爲nil,您不需要再次初始化它。這只是一個方便(儘管,如果你不熟悉static限定符)顯然有一個變量只能初始化一次。

相關問題