ios developer tiny share-20160912

本文探讨了Objective-C中循环引用的问题及其解决方案。通过使用弱引用打破强引用循环,避免内存泄漏。具体介绍了UITableView如何通过弱引用解决其与代理之间的循环引用问题。

今天讲Objective-C的循环引用的问题,以及解决方案,即使用弱引用。

Avoid Strong Reference Cycles
Although strong references work well for one-way relationships between objects, you need to be careful when working with groups of interconnected objects. If a group of objects is connected by a circle of strong relationships, they keep each other alive even if there are no strong references from outside the group.

One obvious example of a potential reference cycle exists between a table view object (UITableView for iOS and NSTableView for OS X) and its delegate. In order for a generic table view class to be useful in multiple situations, it delegates some decisions to external objects. This means it relies on another object to decide what content it displays, or what to do if the user interacts with a specific entry in the table view.

A common scenario is that the table view has a reference to its delegate and the delegate has a reference back to the table view, as shown in Figure 3-7.

Figure 3-7  Strong references between a table view and its delegate


A problem occurs if the other objects give up their strong relationships to the table view and delegate, as shown in Figure 3-8.

Figure 3-8  A strong reference cycle


Even though there is no need for the objects to be kept in memory—there are no strong relationships to the table view or delegate other than the relationships between the two objects—the two remaining strong relationships keep the two objects alive. This is known as a strong reference cycle.

The way to solve this problem is to substitute one of the strong references for a weak reference. A weak reference does not imply ownership or responsibility between two objects, and does not keep an object alive.

If the table view is modified to use a weak relationship to its delegate (which is how UITableView and NSTableView solve this problem), the initial object graph now looks like Figure 3-9.

Figure 3-9  The correct relationship between a table view and its delegate


When the other objects in the graph give up their strong relationships to the table view and delegate this time, there are no strong references left to the delegate object, as shown in Figure 3-10.

Figure 3-10
 Avoiding a strong reference cycle


This means that the delegate object will be deallocated, thereby releasing the strong reference on the table view, as shown in Figure 3-11.

Figure 3-11  Deallocating the delegate


Once the delegate is deallocated, there are no longer any strong references to the table view, so it too is deallocated.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值