0

NSDateFormatter includes the following convenience method:

+ (NSString *)localizedStringFromDate:(NSDate *)date dateStyle:(NSDateFormatterStyle)dateStyle timeStyle:(NSDateFormatterStyle)timeStyle

The documentation states that using this method is the same as explicitly doing this:

NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setFormatterBehavior:NSDateFormatterBehavior10_4];
[formatter setDateStyle:dateStyle];
[formatter setTimeStyle:timeStyle];
NSString *result = [formatter stringForObjectValue:date];

Now, I have read in various places that initialising an NSDateFormatter object has quite an overhead. Does anyone know if the localizedStringFromDate:etc class method has the same overhead i.e. it causes the instantiation of a new NSDateFormatter object under the covers every time it is called?

David Jones - iPushPull
  • 2,819
  • 1
  • 22
  • 24

1 Answers1

1

I am using my NSDateFormatters as static variables which I initialize lazily. Like this the init routine is only called once:

static NSDateFormatter *formatter = nil;
if (!formatter) {
   formatter = [[NSDateFormatter alloc] init];
   [formatter setDateStyle:dateStyle];
   [formatter setTimeStyle:timeStyle];
}
NSString *result = [formatter stringFromDate:date]; 
// reuse
[formatter setDateStyle:anotherDateStyle];
[formatter setTimeStyle:anotherTimeStyle];
NSString *anotherResult = [formatter stringFromDate:anotherDate]; 
Mundi
  • 79,884
  • 17
  • 117
  • 140
  • Thanks - this is the kind of thing I normally do (or use a singleton). I was just curious about what was happening under the covers when the class method is called. I will try to work it out myself. – David Jones - iPushPull May 30 '12 at 18:50
  • This is not thread-safe. [See How to minimize the costs for allocating and initializing an NSDateFormatter?](http://stackoverflow.com/questions/4442074/how-to-minimize-the-costs-for-allocating-and-initializing-an-nsdateformatter) for discussion – Kirby Todd Apr 30 '14 at 08:05
  • The referenced question is really quite a different scenario, involving stress testing the creation of many date formatters. In this case, there is only one. – Mundi May 01 '14 at 11:06