2010-09-20 84 views
0

我在看這段代碼:Objective-C的保留澄清

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 *),但是當我調用[控制器發佈]不是self.viewControllers以及設置self.viewControllers =控制器會自動保留該內存?

回答

2

點符號(self.foo = bar;)等於調用[self setFoo:bar];。如果您的屬性被聲明爲保留其值,那麼您的視圖控制器將在這種情況下保留該數組,並在設置新值後釋放它。

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