代码如下,在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
没有了持有者了,也是被释放了。
所以,请问有什么方法可以解决这个吗?
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 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
The problem with vc being released is that vc is not held by other objects. The correct solution should be to find the vc from the current navigationController or other vc stack, and then operate the vc.
Use copy for the block attribute, and then add __strong __typeof(weaksSelf) strongSelf = weakSelf, but the logic of your code is weird
Modify it in your block with __strong __typeof(&*weaksSelf) strongSelf = weakSelf
Let’s not talk about the issue of circular references
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?