Last active
December 10, 2015 13:04
-
-
Save luca-bernardi/4190354 to your computer and use it in GitHub Desktop.
Threadsafe NSDateFormatter's instance cache
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
As Apple said [NSDateFormatter init] is very expensive (https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/DataFormatting/Articles/dfDateFormatting10_4.html#//apple_ref/doc/uid/TP40002369-SW10) | |
In Apple's code is used a static const, but since NSDateFormatter | |
isn't thread safe a better approach is to use Thread local store (http://developer.apple.com/library/ios/#documentation/Cocoa/Conceptual/Multithreading/CreatingThreads/CreatingThreads.html#//apple_ref/doc/uid/10000057i-CH15-SW4) | |
to cache the NSDateFormatter instance | |
*/ | |
NSString * const kCachedDateFormatterKey = @"CachedDateFormatterKey"; | |
+ (NSDateFormatter *)dateFormatter | |
{ | |
NSMutableDictionary *threadDictionary = [[NSThread currentThread] threadDictionary]; | |
NSDateFormatter *dateFormatter = [threadDictionary objectForKey:kCachedDateFormatterKey]; | |
if (!dateFormatter) { | |
dateFormatter = [[NSDateFormatter alloc] init]; | |
NSLocale *enUSPOSIXLocale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"]; | |
[dateFormatter setLocale:enUSPOSIXLocale]; | |
[dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss.SSSSS"]; | |
[threadDictionary setObject:dateFormatter forKey:kCachedDateFormatterKey]; | |
} | |
return dateFormatter; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
_Thread_local
/thread_local
(depending on your compiler environment)static
variables may be an acceptable alternative to the thread dictionary; they can clarify the logic quite pleasantly: