Objective-C保留澄清

时间:2010-09-20 14:58:28

标签: iphone objective-c retain

我正在看这段代码:

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

稍后......

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

我看到self.viewControllers和控制器现在指向相同的已分配内存(类型为NSMutableArray *),但是当我调用[controllers release]时,也不会释放self.viewControllers,或者正在设置self.viewControllers =控制器会自动保留该内存吗?

2 个答案:

答案 0 :(得分:2)

点符号(self.foo = bar;)等于调用[self setFoo:bar];。如果声明属性保留其值,那么viewcontrollers将在这种情况下保留数组,并在设置新值后释放它。

答案 1 :(得分:1)

我将假设viewControllers是保留相关值的属性。

@property (nonatomic, retain) NSArray *viewControllers;

基于此,让我们分析一下您的代码段的保留计数:

// 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

稍后......

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