Created
October 12, 2013 08:20
-
-
Save 0oneo/6947359 to your computer and use it in GitHub Desktop.
NSDateFormatter is not thread safe
This file contains 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
// test code that generate the error | |
for (int i = 0; i < 1000; i++) { | |
NSDate *date= [NSDate date]; | |
NSString *queueName = [NSString stringWithFormat:@"queue%i", i]; | |
dispatch_queue_t testqueue = dispatch_queue_create([queueName cStringUsingEncoding:NSUTF8StringEncoding], NULL); | |
dispatch_async(testqueue, ^{ | |
NSDateFormatter *ndf = [BXAppDelegate dateFormatter]; | |
DDLogInfo(@"%@", [ndf stringFromDate:date]); | |
}); | |
} | |
// Try 1 code wrong | |
+ (NSDateFormatter *)dateFormatter | |
{ | |
static NSDateFormatter *dateFormatter = nil ; | |
if (dateFormatter == nil) | |
{ | |
dateFormatter = [[NSDateFormatter alloc] init] ; | |
[dateFormatter setLocale: [[NSLocale alloc] initWithLocaleIdentifier: @"en_GB"] ] ; | |
[dateFormatter setDateFormat: @"YYYY-MM-dd HH:mm:ss ZZZ"] ; | |
} | |
return dateFormatter ; | |
} | |
// right try | |
+ (NSDateFormatter *)dateFormatter2 | |
{ | |
NSMutableDictionary *threadDic = [[NSThread currentThread] threadDictionary]; | |
NSDateFormatter *dateFormatter = threadDic[@"BXMyDateFormatter"]; | |
if (dateFormatter == nil) { | |
dateFormatter = [[NSDateFormatter alloc] init]; | |
[dateFormatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_GB"]]; | |
[dateFormatter setDateFormat:@"YYYY-MM-dd HH:mm:ss ZZZ"]; | |
[threadDic setObject:dateFormatter forKey:@"BXMyDateFormatter"]; | |
} | |
return dateFormatter; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment