ITeye博客

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

82934162 · 2015-05-27 16:39 · Objective-C · iOS · 移动开发 · Markdown

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

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。