James
James

Reputation: 1689

Objective-C retain clarification

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?

Upvotes: 0

Views: 147

Answers (2)

vfn
vfn

Reputation: 6066

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 {
    [self.viewControllers release]; // controllers (released) -> retainCount-- == 0 (zero == no leak == no crash by over-release)
    ...
}

Upvotes: 1

Toastor
Toastor

Reputation: 8990

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.

Upvotes: 2

Related Questions