2011-05-10 64 views
1

我是iOS和objective-C的新手,儘管我一直在努力瞭解內存管理,但我對自己感到失望,因爲我仍然需要完整的畫面......我的問題在於我不明白如何保留對象的屬性與保留整個對象有關。讓我們以下面的代碼爲例:在ios中的內存管理目標c

@interface TestObject:NSObject { //TestObject declaration 
    NSNumber *firstNumber; 
} 

@property (nonatomic, retain) NSNumber *firstNumber; 

@end 

@synthesize firstNumber; 

-(void) dealloc //Use standard synthesized getter and setter, write only custom 
       //dealloc     
{ 
[firstNumber release]; 
} 

...和下​​面的代碼使用它:

-(IBAction) runClicked: (id) sender 
{ 
TestObject *to1=[[TestObject alloc ] init]; 
to1.firstNumber=[NSNumber numberWithInt:10]; //retain count 1 on firstnumber 
NSNumber *num=[to1.firstNumber retain]; //retain count 2 on firstnumber 
[to1 release]; //retain count 1 on firstnumber because of 1 release in dealloc 
} 

我跑的代碼的分析,也跟着跑漏儀的程序和兩者都沒有發現泄漏。 firstnumber沒有泄漏(在主對象釋放後可以通過num訪問),因爲* num在函數體的末尾被銷燬後,任何指針都不能使用該數字?

非常感謝你的時間! 問候, 弗羅林。

回答

0

不,不存在泄漏,因爲第一個數字是自動釋放對象。

+0

感謝您的回答,但稍等: – user729404 2011-05-11 06:40:58

+0

我知道to1.firstNumber = [NSNumber numberWithInt:10]的右側正在自動釋放已創建的數字,但由於該屬性聲明爲(非原子,保留),因此isn to1.firstNumber的發佈計數仍增加到1?如果我還在右側使用了一個alloc類型的構造函數,那麼發佈計數實際上是2.我在哪裏錯了? – user729404 2011-05-11 06:52:34