I’m going through the Big Nerd Ranch for IOS (3rd edition). And I’m on the ARC Memory Management chapter. It’s trying to explain retain cycles and it has us modify a short console application like so:
Header for BNRItem:
@interface BNRItem : NSObject
{
NSString *itemName;
NSString *serialNumber;
int valueInDollars;
NSDate *dateCreated;
BNRItem *containedItem;
BNRItem *container;
}
+ (id)randomItem;
- (void)setItemName:(NSString *)str;
- (NSString *)itemName;
- (void)setSerialNumber:(NSString *)str;
- (NSString *)serialNumber;
- (void)setValueInDollars:(int) i;
- (int)valueInDollars;
- (void)setContainedItem:(BNRItem *)i;
- (BNRItem *)containedItem;
-(void)setContainer:(BNRItem *)i;
- (BNRItem *)container;
- (NSDate *)dateCreated;
- (id)initWithItemName:(NSString*)name valueInDollars:(int)value serialNumber:(NSString *)sNumber;
- (id)initWithItemName:(NSString *)name andSerialNumber:(NSString *)sNumber;
@end
main file:
int main(int argc, const char * argv[])
{
@autoreleasepool {
NSMutableArray *items = [[NSMutableArray alloc]init];
BNRItem *backpack = [[BNRItem alloc] init];
[backpack setItemName:@"Backpack"];
[items addObject:backpack];
BNRItem *calculator = [[BNRItem alloc]init];
[calculator setItemName:@"Calculator"];
[items addObject:calculator];
[backpack setContainer:calculator];
NSLog(@"Setting items to nil");
items = nil;
}
return 0;
}
Now after this it says: “Per our understanding of memory management so far, both BNRItems should be destroyed along with their instance variables when items is set to nil”. It had prior to this have us override (void) dealloc to print out when our BNRItem gets destroyed.
So I run it and I’m suppose to see because backpack now has a strong reference to calculator neither get destroyed. Now in the console I see both getting destroyed but I think it’s because they get destroyed when the application ends. When I do a break point after setting items to nil nothing is getting destroyed. Which is what the book says should happen… but then it makes me set container to
__weak BNRItem *container
and then when I run it still nothing gets destroyed. I’m assuming because there are still pointers to it that I did not set to nil? Even though the book does not mention to do so at this point. So I understand the books explanation (I think), but in practice it’s not happening.
I trusted the auto completion.
should have been