Allocating NSDateFormatter (or NSNumberFormatter) is relatively slow and
cellForRowAtIndexPath runs for every cell. So, allocating formatters in cellForRowAtIndexPath can be a significant contributor to jerky scrolling.To smooth scrolling, I tried allocating them outside cellForRowAtIndexPath,
by making them a class variable and allocating them in viewWillAppear and releasing them in viewWillDisappear (see code below). But that produce leaks in the formatters.Where is the best place to declare/allocate/release formatters used in cellForRowAtIndexPath?
//in myNavigationViewController.m:
NSDateFormatter *myDateFormatter;
-...viewWillAppear...{
if(myDateFormatter){ //Solution: add this check.
[myDateFormatter release];
}
myDateFormatter = [[NSDateFormatter alloc] init];
[myDateFormatter setDateStyle:NSDateFormatterShortStyle];
[myDateFormatter setTimeStyle:NSDateFormatterShortStyle];
if(locale){ //Solution: add this check.
[locale release];
}
locale = [NSLocale currentLocale];
[myDateFormatter setLocale:locale];
}
开发者_如何学运维-...cellForRowAtIndexPath... {
cell.myDateLabel.text = [myDateFormatter stringFromDate:_date];
}
-...viewWillDisappear...{
// [myDateFormatter release]; //Solution: remove this line
}
-...dealloc {
[myDateFormatter release]; //Solution: add these 2 lines.
[locale release];
}
It shouldn't leak at all so long as you remember to deallocate it in -dealloc
.
精彩评论