ios - 类方法中使用了block,如何避免循环引用?
PHP中文网
PHP中文网 2017-04-18 09:55:43
0
4
859

代码如下,在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];
    });
}

尝试:

  1. vc使用修饰词 __block,但不能解决问题,而且__block修饰后,vc仍然是强引用的。

  2. vc使用修饰词__weak,确实消除了Xcode关于循环引用的告警。但netRequestCallBack 运行时,会发现vc已经被为nil
    我理解出现这种情况,是在类方法完成后,vc没有了持有者了,也是被释放了。

所以,请问有什么方法可以解决这个吗?

PHP中文网
PHP中文网

认证0级讲师

reply all(4)
迷茫

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

__weak

to declare the variables captured by the block. That’s

__weak AUIViewController *tmpVC = vc;
vc.mainModel.netRequestCallBack = ^(NSError *error){
    [[tmpVC navigationController] pushViewController:vc animated:YES];
};

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

Peter_Zhu

Modify it in your block with __strong __typeof(&*weaksSelf) strongSelf = weakSelf

小葫芦

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?

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template