views:

42

answers:

2

I'm looking at this code:

NSMutableArray *controllers = [[NSMutableArray alloc] init];
for (unsigned i = 0; i < kNumberOfPages; i++) {
    [controllers addObject:[NSNull null]];
}
self.viewControllers = controllers;
[controllers release];

Later on...

- (void)dealloc {
    [viewControllers release];
    ...
}

I see that self.viewControllers and controllers now point to the same allocated memory (of type NSMutableArray *), but when I call [controllers release] isn't self.viewControllers released as well, or is setting self.viewControllers = controllers automatically retains that memory?

+2  A: 

The dot-notation (self.foo = bar;) equals calling [self setFoo:bar];. If your property is declared to retain its value, then your viewcontrollers will retain the array in this case, and release it once you set a new value.

Toastor
+1  A: 

I will assume that viewControllers is a property that retains the associated value.

@property (nonatomic, retain) NSArray *viewControllers;

Based on this, let's analyze the retain count on your piece of code:

// controllers -> retainCount == 0
NSMutableArray *controllers = [[NSMutableArray alloc] init]; // controllers (alloc) -> retainCount++ == +1
for (unsigned i = 0; i < kNumberOfPages; i++) {
    [controllers addObject:[NSNull null]];
}
self.viewControllers = controllers; // controllers (retained by viewControllers) -> retainCount++ == +2
[controllers release]; // controllers (released) == retainCount-- == +1

Later on...

- (void)dealloc {
    [viewControllers release]; // controllers (released) -> retainCount-- == 0 (zero == no leak == no crash by over-release)
    ...
}
vfn