目标c中的ARC循环引用使用委托 [英] ARC circular reference in objective-c uses delegate

查看:142
本文介绍了目标c中的ARC循环引用使用委托的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好!

我试图在我的应用程序中使用委托。我的项目使用 ARC

I tried to use a delegate in my app. My project uses ARC

例如,我有协议X​​和两个使用它的对象。
在对象 B 中,我创建了一个对象 A 的实例,并设置委托自身(A.delegate = self)
在运行时,我调用一个方法callBack (在这一点上,我的委托对象是 B )。之后,他们都执行 -showResult 方法。

For example, I have protocol X and two object which uses it. In object B I created an instance for object A and set delegate self (A.delegate = self) In runtime I invoke a method callBack (in this point my delegate object is B). After that they all execute the -showResult method.

在什么点创建循环引用?我明白这是说明者 strong 的问题,但我不明白发生了什么时间,以及如何追踪。

At what point is a circular reference formed? I understand that this is a problem with the specifier strong, but I don't understand what time it happened, and how to track it.

谢谢!

推荐答案

如果两个对象都保持强烈的引用(即彼此保持一致),则可以在你手上有所谓的保留周期。两个对象都不会被释放,因为另一个对象有很强的引用(保留它),所以它永远不会放弃其引用(释放)另一个对象。

If two objects both maintain strong references to each other (that is, they retain each other), you may have what's known as a 'retain cycle' on your hands. Neither object will ever be deallocated because the other has a strong reference to it (retains it), and so it will never give up its reference (release) the other object.

这种情况与代表很常见,其中一个对象(称为A)创建另一个对象(B)并将其设置为B的委托。如果A对B有很强的引用,所以B不会被释放,而B也有很强的参考A,你有一个参考周期。为了避免这种情况,对于不保留或强烈引用其代表的对象来说,这是常见的。让B参考一个弱而不是强者,问题就会消失。

This situation is common with delegates, where one object (call it A) creates another (B) and sets itself as B's delegate. If A has a strong reference to B so that B won't get deallocated, and B also has a strong reference to A, you have a reference cycle. In order to avoid that, it's common for objects not to retain or keep strong references to their delegates. Make B's reference to A weak instead of strong and the problem goes away.

这篇关于目标c中的ARC循环引用使用委托的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆