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

被折叠的 条评论
为什么被折叠?



