非线程安全对象: https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/Multithreading/ThreadSafetySummary/ThreadSafetySummary.html
解决crash的方法可以用threadDictionary或者加锁.
加锁会造成线程阻塞,用threadDictionary会造成内存增加.根据实际情况取舍.
用threadDictionary:不再访问同一个不安全的对象,而是每一个线程都拥有一个对象,既可以提高效率(一个线程创建一次该对象就够了),也可以保证不crash.
+ (NSDateFormatter *)currentDateFormatter { NSMutableDictionary *threadDictionary = [[NSThread currentThread] threadDictionary] ; NSDateFormatter *dateFormatter = [threadDictionary objectForKey: @"DDMyDateFormatter"] ; if (dateFormatter == nil) { dateFormatter = [[NSDateFormatter alloc] init] ; [dateFormatter setLocale: [[[NSLocale alloc] initWithLocaleIdentifier: @"en_GB"] autorelease]] ; [dateFormatter setDateFormat: @"YYYY-MM-dd HH:mm:ss ZZZ"] ; [threadDictionary setObject: dateFormatter forKey: @"DDMyDateFormatter"] ; } return dateFormatter ; }
PS: NSDateFormatter在iOS7以后已经成了线程安全的类.