Graphics Programs Reference
In-Depth Information
The two
BNRItem
s cannot be accessed by any other part of the application (in this case,
the
main
function), yet they still exist in their own little world doing nothing useful.
Moreover, because they cannot be destroyed, neither can the other objects that their in-
stance variables point to.
To fix this problem, one of the pointers between the
BNRItem
s needs to be a weak refer-
ence. To decide which one should be weak, think of the objects in the cycle as being in a
parent-child relationship. In this relationship, the parent can own its child, but a child
should never own its parent. In our retain cycle, the backpack is the parent, and the calcu-
lator is the child. Thus, the backpack can keep its strong reference to the calculator (
con-
tainedItem
), but the calculator's reference to the backpack (
container
) should be
weak.
To declare a variable as a weak reference, we use the
__weak
attribute. In
BNRItem.h
,
change the
container
instance variable to be a weak reference.
__weak
BNRItem *container;
Build and run the application again. This time, the objects are destroyed properly.