[OBSOLETE INFORMATION! SEE UPDATES!]
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 0x300cafa4 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 for something like
That should work out nicely for you.
On iOS 7 and later NSDateFormatter is thread safe.
On OS X v10.9 and later NSDateFormatter is thread safe so long as you are using the modern behavior in a 64-bit app.
On earlier versions of the operating system, or when using the legacy formatter behavior or running in 32-bit on OS X, NSDateFormatter is not thread safe and you therefore must not mutate a date formatter simultaneously from multiple threads.
If you’re parsing ISO-8601(JSON) dates, try Date Parsing Performance: NSDateFormatter vs. SQLite instead.
FormatterKit has time intervals, and oodles of other goodies.
- A very brief introduction to date formatting in Swift and iOS
- How to work with dates and times in Swift, part one
- part two: Calculations with dates
- part three: Making date arithmetic more Swift-like
- part four: A more Swift-like way to get the time interval between two dates
Tempo: “Date and time manager for iOS/OSX written in Swift.”
CVCalendarKit: “A wrapper around NSDate which provides a convenience way for dealing with dates.”
SwiftDate: “Easy NSDate Management in Swift.”