Clarification regarding setContainedItem:


Hello. First of all, this is a fantastic book, but I can’t help but be a little confused at something in chapter 3. In the “Strong and Weak References” section, there are a couple new instance variables and accessors added. Now, setContainedItem: reads:

- (void)setContainedItem:(BNRItem *)i { containedItem = i; // When given an item to contain, the contained // item will be given a pointer to its container [i setContainer:self]; }

Can someone explain to me what the point of the [i setContainer:self]; is?


The idea is that each item will not only know what it contains, but also what contains it (if anything). Thus, the setContainer message is sent so that the contained item knows about its container.

You could leave that responsibility to the code that is creating the objects, but that runs the risk that the caller will forget to set both ends of the connection.