经典问题
@interface ViewController ()
@property (strong,nonatomic) NSString *str;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
dispatch_queue_t queue = dispatch_queue_create("con", DISPATCH_QUEUE_CONCURRENT);
for (int i= 0; i < 1000000; i++) {
dispatch_async(queue, ^{
self.str = [NSString stringWithFormat:@"str =%d",i];//每次不同值
});
}
}
因为是异步并行队列,而且str属性是非原子性的,系统会开启多条线程来执行Block代码,运行的时候,几率出现crash现象。
此时crash堆栈如下
* thread #9, queue = 'com.apple.root.user-initiated-qos', stop reason = EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)
* frame #0: 0x00007fff204a07bf CoreFoundation`___forwarding___.cold.2 + 87
frame #1: 0x00007fff20421f46 CoreFoundation`___forwarding___ + 1253
frame #2: 0x00007fff20424068 CoreFoundation`__forwarding_prep_0___ + 120
frame #3: 0x00007fff2019101b libobjc.A.dylib`AutoreleasePoolPage::releaseUntil(objc_object**) + 175
frame #4: 0x00007fff20190f0a libobjc.A.dylib`objc_autoreleasePoolPop + 185
frame #5: 0x000000010f9af9b1 libdispatch.dylib`_dispatch_last_resort_autorelease_pool_pop + 27
frame #6: 0x000000010f9c199c libdispatch.dylib`_dispatch_root_queue_drain + 1523
frame #7: 0x000000010f9c1e6d libdispatch.dylib`_dispatch_worker_thread2 + 135
frame #8: 0x00007fff5e7899f7 libsystem_pthread.dylib`_pthread_wqthread + 220
frame #9: 0x00007fff5e788b77 libsystem_pthread.dylib`start_wqthread + 15
线上出现此种Crash堆栈,一般对定位crash造成很大困扰,难以定位问题。
原因:因为对self.str进行重新赋值的时候,会调用内部的setter方法的release
方法,如果线程A调用release
方法的时候,对象已经释放了,如果线程B在这个时刻调用了release
方法,就出现crash现象。(访问一个已经释放的对象,会出现野指针问题EXC_BAD_ACCESS)
MRC的Setter与getter方法
//非原子性
- (void)setStr:(NSString *)str {
[str retain];
[_str release];
_str = str;
}
- (NSString *)str {
return _str;
}
//原子性
- (NSString *) str {
NSString *str = nil;
@synchronized(self) {
str = [[_str retain] autorelease];
}
return str;
}
- (void) setStr:(UITextField *)str {
@synchronized(self) {
[str retain];
[_str release];
_str = str;
}
}
就算上述的代码运行在ARC环境下,一样会导致crash现象,因为ARC的retain和release是由编辑器在编译的时候自动加上去的,最后一样会有retain和release方法。
解决方法
把self.str属性改成原子性的,或者给Block加锁,或者self.str属性改成weak属性。
如下,在修改str
值的外面加锁。
@interface ViewController ()
@property (strong,nonatomic) NSString *str;
@end
dispatch_queue_t queue = dispatch_queue_create("con", DISPATCH_QUEUE_CONCURRENT);
for (int i= 0; i < 1000000; i++) {
dispatch_async(queue, ^{
@synchronized(self) {//入参self为所要保护的对象,内部其实是一个递归锁
// task
self.str = [NSString stringWithFormat:@"str =%d",i];
}
});
}
注意:atomic
不是绝对安全,只是在setter中增加锁而已。
如果对象不通过setter
更改,一样会出现几率crash,如下,通过_str
修改。
@interface ViewController ()
@property (strong,atomic) NSString *str;
@end
dispatch_queue_t queue = dispatch_queue_create("con", DISPATCH_QUEUE_CONCURRENT);
for (int i= 0; i < 1000000; i++) {
dispatch_async(queue, ^{
//直接修改str的值
self->_str = [NSString stringWithFormat:@"str =%d",i];
});
}