简体   繁体   中英

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?

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.

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)
    ...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM