简体   繁体   English

Objective-C保留澄清

[英]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? 我看到self.viewControllers和控制器现在指向同一分配的内存(类型为NSMutableArray *),但是当我调用[controllers release]时,self.viewControllers也未释放,或者设置了self.viewControllers =控制器会自动保留那记忆?

The dot-notation ( self.foo = bar; ) equals calling [self setFoo:bar]; 点号( self.foo = bar; )等于调用[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. 我将假定viewControllers是保留相关值的属性。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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