Skip to content

Instantly share code, notes, and snippets.

@0oneo
Created October 12, 2013 08:20
Show Gist options
  • Save 0oneo/6947359 to your computer and use it in GitHub Desktop.
Save 0oneo/6947359 to your computer and use it in GitHub Desktop.
NSDateFormatter is not thread safe
// 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