今天闲逛,突然捕获一个帖子说NSDateFormatter线程不安全,为了线程安全最好每个线程用自己的对象,如果需要用到的话
NSMutableDictionary *threadDictionary = [[NSThread currentThread] threadDictionary];
NSDateFormatter *dateFormatter = threadDictionary[@”mydateformatter”];
if(!dateFormatter){
@synchronized(self){
if(!dateFormatter){
dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@”yyyy-MM-dd HH:mm:ss”];
[dateFormatter setTimeZone:[NSTimeZone timeZoneWithName:@”Asia/Shanghai”]];
threadDictionary[@”mydateformatter”] = dateFormatter;
}
}
}
然后看了看文档,发现线程安全问题已经基本解决了:
https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSDateFormatter_Class/index.html#//apple_ref/occ/cl/NSDateFormatter
Thread Safety
On iOS 7 and later NSDateFormatter
is thread safe.
On OS X 10.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.