iOS多线程访问非线程安全对象的crash

多个线程在访问同一个非线程安全对象时,有可能会crash.
非线程安全对象: 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以后已经成了线程安全的类.








猜你喜欢

转载自borissun.iteye.com/blog/2214828