开发者

How cellForRowAtIndexPath can reuse formatters (to improve scrolling)?

开发者 https://www.devze.com 2023-01-27 01:00 出处:网络
Allocating NSDateFormatter (or NSNumberFormatter) is relatively slow and cellForRowAtIndexPath runs for every cell.

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消