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

多个线程在访问同一个非线程安全对象时,有可能会crash.
非线程安全对象:[url]https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/Multithreading/ThreadSafetySummary/ThreadSafetySummary.html[/url]

解决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
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值