Graphics Programs Reference
In-Depth Information
Strong and Weak References
So far, we've said that anytime a pointer variable stores the address of an object, that object
has an owner and will stay alive. This is known as a strong reference . However, a variable
can optionally not take ownership of an object it points to. A variable that does not take
ownership of an object is known as a weak reference .
A weak reference is useful for an unusual situation called a retain cycle . A retain cycle oc-
curs when two or more objects have strong references to each other. This is bad news.
When two objects own each other, they will never be destroyed by ARC. Even if every oth-
er object in the application releases ownership of these objects, these objects (and any ob-
jects that they own) will continue to exist by virtue of those two strong references.
Thus, a retain cycle is a memory leak that ARC needs your help to fix. You fix it by mak-
ing one of the references weak. Let's introduce a retain cycle in RandomPossessions to see
how this works. First, we'll give BNRItem instances the ability to hold another BNRItem
(so we can represent things like backpacks and purses). In addition, a BNRItem will know
which BNRItem holds it. In BNRItem.h , add two instance variables and accessors
@interface BNRItem : NSObject
{
NSString *itemName;
NSString *serialNumber;
int valueInDollars;
NSDate *dateCreated;
BNRItem *containedItem;
BNRItem *container;
}
+ (id)randomItem;
- (id)initWithItemName:(NSString *)name
valueInDollars:(int)value
serialNumber:(NSString *)sNumber;
- (void)setContainedItem:(BNRItem *)i;
- (BNRItem *)containedItem;
- (void)setContainer:(BNRItem *)i;
- (BNRItem *)container;
Implement the accessors in BNRItem.m .
- (void)setContainedItem:(BNRItem *)i
{
containedItem = i;
// When given an item to contain, the contained
Search WWH ::




Custom Search