apple官网文档:
Thread Safety
On iOS 7 and later NSDate
is thread safe.
In macOS 10.9 and later NSDate
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 in macOS, NSDate
is not thread safe, and you therefore must not mutate a date formatter simultaneously from multiple threads.
说明:ios7及以上版本 NSDateFormatter是线程安全的!之前的版本确定不是线程安全的!所以以后不要管它的线程安全问题了!
========================================================转载=====================================================================
经常需要将NSDate和NSString进行互转,一般我们会这么写:
- NSDate转NSString
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@”yyyy-MM-dd’T’HH:mm:ss”];
[dateFormatter setTimeZone:[NSTimeZone timeZoneWithName:@”Asia/Shanghai”]];
return [dateFormatter dateFromString:dateString];
- NSString转NSDate
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
NSTimeZone *timeZone = [NSTimeZone defaultTimeZone];
[dateFormatter setTimeZone:timeZone];
[dateFormatter setDateFormat:@”yyyy-MM-dd HH:mm:ss Z”];
return [dateFormatter stringFromDate:date];
- 延迟转换并Cache
即只有在UI需要使用转换结果时再执行转换,并将结果缓存起来。 - NSDateFormatter对象只生成1次
static NSDateFormatter *dateFormatter = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
dateFormatter = [[NSDateFormatter alloc] init];
});
[dateFormatter setDateFormat:@”yyyy-MM-dd’T’HH:mm:ss”];
[dateFormatter setTimeZone:[NSTimeZone timeZoneWithName:@”Asia/Shanghai”]];
return [dateFormatter dateFromString:dateString];
貌似也挺容易的,哈哈经过上面的改造后,你会发现性能得到了显著提升,非常高兴的给老大发布新版本,很快老大又过来把你劈头盖脸地训了一顿:“怎么老是Crash,这么不稳定?赶紧fix”。
一查CrashReport,发现在[dateFormatter dateFromString:dateString]这里出了问题。这就奇怪了?系统函数库也有bug么?
当然不是了,这是因为 NSDateFormatter不是线程安全的 ,请查看 https://developer.apple.com/library/mac/documentation/cocoa/conceptual/Multithreading/ThreadSafetySummary/ThreadSafetySummary.html ,里面列出了线程安全和不安全的类。当多个线程同时访问1个NSDateFormatter对象时,有可能会Crash。
那怎么办?不要泄气,咱们给每个线程准备1个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;
}
}
}
发现没有,上面使用了 double-check 技术哦,哈哈,这里千万不要再用dispatch_once哈。