ios开发 循环引用 检测_iOS开发,为避免循环引用有时我们会在block里使用weakSelf...

用__strong是为了保证对象在block执行前不被释放.

Demo: A 控制器(present)跳转到B, B dismiss回来.block里面有延时操作.

使用没__strong时, 在B控制器dismiss, secondVC释放为nil, 1.0秒后block执行, 此时weakVC为nil.

使用__strong, 调用dismiss, 由于block有强引用, secondVC不被释放(不是nil), 1.0秒后执行完block, 释放vc.

A控制器代码:

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event

{

SecondViewController *secondVC = [SecondViewController new];

__weak SecondViewController *weakVC = secondVC;

secondVC.secondBlock = ^(){

// // 在SecondViewController界面调用dismiss后,依然可以正常输出, VC dealloc

// __strong SecondViewController *strongVC = weakVC;

// dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{

// NSLog(@"%@",strongVC.view);

// });

// SecondViewController调用dismiss后被释放为nil, 打印为nil

dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{

NSLog(@"%@",weakVC.view);

});

};

[self presentViewController:secondVC animated:YES completion:nil];

}

B控制器代码:

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event

{

self.secondBlock();

[self dismissViewControllerAnimated:YES completion:nil];

}

测试结果:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值