I wouldn't use a static variable, because then you'll almost certainly end up with a memory leak. Instead, I would use two NSDateFormatter *
instance variables or properties on that controller object that are instantiated only on demand. When the view unloads or the controller is deallocated, you can then release them.
For example:
@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
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…