0

During the call to tableView:cellForRowAtIndexPath: I'm calling this function to format a date into a time:

- (NSString *)_formatDate:(NSDate *)date withString:(NSString *)string {
    NSLocale *locale = [NSLocale currentLocale];
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    NSString *dateFormat = [NSDateFormatter dateFormatFromTemplate:string options:0 locale:locale];
    [formatter setDateFormat:dateFormat];
    [formatter setLocale:locale];
    return [formatter stringFromDate:date];
}

I'm passing in the date for the row as well as the string @"HH:mm".

Unfortunately this seems to be lagging my table view. A similar thing is happening in my section headers where I am formatting to a full date.

Is there any reason this should be lagging my app so much? Are any of these calls particularly intensive?

Thanks

Tom

Thomas Clayson
  • 29,657
  • 26
  • 147
  • 224

1 Answers1

3

There is word that creating date formatters is expensive. Use an instance variable and set up a single date formatter in viewDidLoad, then reuse that same formatter each time you need one. Or lazy load one as needed.

If it's not the creation that's expensive, but the parsing of the date string, pre-save a parsed copy of your date and use that instead. You'll have to worry about things like location and locale changes with that though, so it gets more complicated.

Community
  • 1
  • 1
nevan king
  • 112,709
  • 45
  • 203
  • 241
  • Lazy instantiation is the way forward. It keeps all the loading of the required object to its own set of functions. If you need to customise/change the object then you know exactly where to do it and it only get's loaded once. – Fogmeister Nov 16 '12 at 11:14
  • This was the problem... there was also some similar code in there for formatting currencies according to the locale which was also contributing to the issue. Got myself a nice smooth table view now, thanks for the help! :) – Thomas Clayson Nov 16 '12 at 14:41