Reputation: 12184
If I have an NSArray of model objects which I display inside of cell. Is it a better practice to pre-calculate data and keep it as a property in the model ?
I see a lot of people doing it. So I follow it as well. But is it always required to specific to certain situations ?
In my current screen, we were to generate a string from date property per model for which we were using NSCalendar and NSDateComponents which possibly could have been heavy every-time we call cellForRowAtIndexPath.
Upvotes: 1
Views: 135
Reputation: 5417
Date formatting is generally regarded as a costly procedure (docs read: Cache Formatters for Efficiency). For these kinds of objects, initializing and caching a single instance is far superior to creating a new one in every call to cellForRowAtIndexPath
. This applies to NSCalenders and NSDateformatters and the like. As long as you are only creating a single instance of your date formatting objects, then using them in cellForRowAtIndexPath
should not be a noticeable hit in performance. Try caching these objects in a class method on your cell or your tableview's delegate like so:
+ (NSDateFormatter *)dateFormatter {
static NSDateFormatter *dateFormatter = nil;
if(!dateFormatter) {
dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"EEEE LLL d, yyyy | h:mma"];
}
return dateFormatter;
}
Upvotes: 4
Reputation: 9857
That methods is called everytime a cell is displayed, so I would remove any long calculation from there.
Much depends on your model.
If you are using CoreData, it is a good choice to think about some transient property holding calculated data specifically for Table Cell. NSManagedObject has awakeFromFecth were you can precalculate things. In addition, there's more like fetched controller and the rest.
If you are not using CoreData, I would try to implement the same mechanism, or the significant part of it, but I read that you already doing it. You could do the calculation asynchronously, within an NSOperation, showing a UIActivityIndicator and then populate table as soon as it finished.
Upvotes: 1
Reputation: 16660
The doc for this method states, that you typically re-use the cell for performance reasons. So you can assume, that it is called over and over.
Upvotes: 1
Reputation: 4641
cellForRowAtIndexPath
is called each time a cell is shown or changed (by scrolling), so the source executed here should not be too much, but it depends on your data. If you have to carry a big number of data and prepare all data before the loading time will increase and your device runs out of memory.
Upvotes: 1