Over a million developers have joined DZone.

iOS Threadsafe Date Formatting

DZone's Guide to

iOS Threadsafe Date Formatting

· Mobile Zone
Free Resource

Download this comprehensive Mobile Testing Reference Guide to help prioritize which mobile devices and OSs to test against, brought to you in partnership with Sauce Labs.

So let’s say you’ve got a project that involves a bunch of repetitive date manipulations, like merging multiple RSS feeds into a single timeline. And having done some timing, and read QA1480, you’re quite aware that


[NSDateFormatter alloc] is insanely expensive. If you’re doing it more than once, YOU’RE DOING IT WRONG.

So you’re doing it only once. And then you find that you start getting a disturbing number of crash reports with terminal lines like

Thread 9 Crashed:
3 libicucore.A.dylib 0×300cafa4 icu::DateFormat::parse(icu::UnicodeString const&, icu::ParsePosition&) const + 120

And that makes you remember, uh-oh … NSDateFormatter is thread-unsafe. Whoops. Well, that throws the above statement for a loop.

However, we can edit that to the actually correct

If you’re doing it more than once per thread, YOU’RE DOING IT WRONG.

by using thread local storage as suggested in this Dropbox forum posting, for something like

+ (NSDateFormatter *)dateReader
   NSMutableDictionary *dictionary = [[NSThread currentThread] threadDictionary];
   NSDateFormatter *dateReader = [dictionary objectForKey:@"SCDateReader"];
   if (!dateReader)
      dateReader = [[[NSDateFormatter alloc] init] autorelease];
      dateReader.locale = [[[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"] autorelease];
      dateReader.timeZone = [NSTimeZone timeZoneForSecondsFromGMT:0];
      dateReader.dateFormat = @"EEE, dd MMM yyyy HH:mm:ss Z";
      [dictionary setObject:dateReader forKey:@"SCDateReader"];
   return dateReader;

+ (NSDateFormatter *)dateWriter
   NSMutableDictionary *dictionary = [[NSThread currentThread] threadDictionary];
   NSDateFormatter *dateWriter = [dictionary objectForKey:@"SCDateWriter"];
   if (!dateWriter)
      dateWriter = [[[NSDateFormatter alloc] init] autorelease];
      dateWriter.locale = [NSLocale currentLocale];
      dateWriter.timeZone = [NSTimeZone defaultTimeZone];
      dateWriter.dateStyle = NSDateFormatterMediumStyle;
      [dictionary setObject:dateWriter forKey:@"SCDateWriter"];
   return dateWriter;

That should work out nicely for you.

Analysts agree that a mix of emulators/simulators and real devices are necessary to optimize your mobile app testing - learn more in this white paper, brought to you in partnership with Sauce Labs.


Published at DZone with permission of Alex Curylo, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}