我需要在tableView:cellForRowAtIndexPath:
中格式化日期和時間。由於創建NSDateFormatter
是一項相當繁重的操作,因此我將它們設置爲靜態。這是以行爲單位格式化日期和時間的最佳方法嗎?在UITableView單元中格式化日期和時間
- (UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = @"Cell";
MyCell*cell = (MyCell*)[self.tableView
dequeueReusableCellWithIdentifier:CellIdentifier
forIndexPath:indexPath];
static NSDateFormatter *dateFormatter = nil;
if (!dateFormatter)
{
dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setLocale:[NSLocale currentLocale]];
[dateFormatter setDateStyle:NSDateFormatterLongStyle];
}
cell.dateLabel = [dateFormatter stringFromDate:note.timestamp];
static NSDateFormatter *timeFormatter = nil;
if (!timeFormatter)
{
timeFormatter = [[NSDateFormatter alloc] init];
[timeFormatter setTimeStyle:NSDateFormatterShortStyle];
}
cell.timeLabel = [timeFormatter stringFromDate:note.timestamp];
return cell;
}
爲什麼使用靜態變量會導致內存泄漏?您能否詳細說明您的建議解決方案?我並沒有真正遵循你的方法。 – memmons 2010-12-15 19:30:01
@Harkonian使用靜態變量會導致內存泄漏,因爲一旦完成使用它們,就無法釋放日期格式化程序。即使您的表格視圖只能看到一次,它的日期格式化程序也會在應用程序的其餘生命週期中停留。我將編輯我的答案,以包含視圖控制器的一些示例代碼。 – 2010-12-15 20:02:39
不確定我們想要擁有和使用的變量是否是內存泄漏本身。 – QED 2013-04-27 14:57:01