我需要在 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;
}
最佳答案
我不会使用静态变量,因为那样你几乎肯定会以内存泄漏告终。相反,我会在该 Controller 对象上使用两个仅按需实例化的 NSDateFormatter *
实例变量或属性。当 View 卸载或 Controller 被释放时,您可以释放它们。
例如:
@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
关于iphone - 在 UITableView 单元格中格式化日期和时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4453550/