Over a million developers have joined DZone.

Threadsafe Date Formatting

DZone 's Guide to

Threadsafe Date Formatting

· Mobile Zone ·
Free Resource

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.


Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

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

{{ parent.tldr }}

{{ parent.urlSource.name }}