Over a million developers have joined DZone.

Threadsafe Date Formatting

DZone's Guide to

Threadsafe Date Formatting

· Mobile Zone
Free Resource

Discover how to focus on operators for Reactive Programming and how they are essential to react to data in your application.  Brought to you in partnership with Wakanda

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.

Learn how divergent branches can appear in your repository and how to better understand why they are called “branches".  Brought to you in partnership with Wakanda


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

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

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

{{ parent.tldr }}

{{ parent.urlSource.name }}