格式化日期和时间

格式化日期和时间

我需要用tableView:cellForRowAtIndexPath:格式化日期和时间。由于创建NSDateFormatter是一项相当繁重的操作,因此我将其设置为静态。这是按行格式化日期和时间的最佳方法吗?

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

最佳答案

我不会使用静态变量,因为这样几乎可以肯定会导致内存泄漏。取而代之的是,我将在控制器对象上使用仅根据需要实例化的两个NSDateFormatter *实例变量或属性。当视图卸载或释放控制器时,可以释放它们。

例如:

@interface MyViewController : UITableViewController {
    NSDateFormatter *dateFormatter;
    NSDateFormatter *timeFormatter;
}

@end

@implementation MyViewController
- (void)viewDidUnload {
    // release date and time formatters, since the view is no longer in memory
    [dateFormatter release]; dateFormatter = nil;
    [timeFormatter release]; timeFormatter = nil;
    [super viewDidUnload];
}

- (void)dealloc {
    // release date and time formatters, since this view controller is being
    // destroyed
    [dateFormatter release]; dateFormatter = nil;
    [timeFormatter release]; timeFormatter = nil;
    [super dealloc];
}

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

    // if a date formatter doesn't exist yet, create it
    if (!dateFormatter) {
        dateFormatter = [[NSDateFormatter alloc] init];
        [dateFormatter setLocale:[NSLocale currentLocale]];
        [dateFormatter setDateStyle:NSDateFormatterLongStyle];
    }

    cell.dateLabel = [dateFormatter stringFromDate:note.timestamp];

    // if a time formatter doesn't exist yet, create it
    if (!timeFormatter) {
        timeFormatter = [[NSDateFormatter alloc] init];
        [timeFormatter setTimeStyle:NSDateFormatterShortStyle];
    }

    cell.timeLabel = [timeFormatter stringFromDate:note.timestamp];
    return cell;
}

@end

09-25 18:45