代码如下,在netRequestCallBack
的中的使用了vc
,Xcode会告警提示: 可能导致循环引用。 请问如何消除?
+ (void)JumpToMe {
dispatch_async(dispatch_get_main_queue(), ^{
AUIViewController *vc = [[AUIViewController alloc] init];
vc.mainModel.netRequestCallBack = ^(NSError *error){
[[vc navigationController] pushViewController:vc animated:YES];
};
[vc.mainModel sendNetworking];
});
}
尝试:
对vc
使用修饰词 __block
,但不能解决问题,而且__block
修饰后,vc
仍然是强引用的。
对vc
使用修饰词__weak
,确实消除了Xcode关于循环引用的告警。但netRequestCallBack
运行时,会发现vc
已经被为nil
。
我理解出现这种情况,是在类方法完成后,vc
没有了持有者了,也是被释放了。
所以,请问有什么方法可以解决这个吗?
迷茫2017-04-18 09:57:43
Whether it is a circular reference has nothing to do with the calling method , it is only related to the reference relationship.
In your example, the reference loop is vc --> mainModel --> netRequestCallBack --> vc. ("-->" indicates reference relationship)The prerequisite for the object to be released is that
the object is not held by other objects. In your example, vc is held by netRequestCallBack, so it will not be released. The way to break the reference cycle is to use
__weakto declare the variables captured by the block. That’s
__weak AUIViewController *tmpVC = vc;
vc.mainModel.netRequestCallBack = ^(NSError *error){
[[tmpVC navigationController] pushViewController:vc animated:YES];
};
高洛峰2017-04-18 09:57:43
Use copy for the block attribute, and then add __strong __typeof(weaksSelf) strongSelf = weakSelf, but the logic of your code is weird
天蓬老师2017-04-18 09:57:43
Modify it in your block with __strong __typeof(&*weaksSelf) strongSelf = weakSelf
高洛峰2017-04-18 09:57:43
Let’s not talk about the issue of circular references
[[vc navigationController] pushViewController:vc animated:YES];
There is a problem with this sentence. If vc is not pushed, will vc.navigationController be Nil? If vc.navgationController is nil, can vc be pushed?