2011-08-19 78 views
0

我對objc非常陌生,我試圖儘可能地理解並在mem管理方面獲得一個很好的例程。分配對象時分配

我的問題是,如果這樣的代碼是危險的(我愛短碼)

NSMutableArray *items = [[NSMutableArray alloc] init]; 

[items addObject:[[UIBarButtonItem alloc] 
        initWithTitle:@"Login" 
        style:UIBarButtonItemStyleBordered 
        target:self 
        action:@selector(tryUserInput)]]; 

[self.toolbar setItems:items animated:TRUE]; 
[self.view addSubview:self.toolbar]; 

[items release]; 

在這些例子中我能找到的人總是創建自己的數組中添加對象,添加它,然後再釋放。如果我分配它並同時添加它,數組將會照顧它?當我完成它時,我會釋放它。另外,我可以這樣寫嗎?

self.navigationItem.backBarButtonItem = [[ALLOC的UIBarButtonItem] initWithTitle:@ 「註銷」 樣式:UIBarButtonItemStyleDone 目標:無 動作:無];

或者我應該附上autorelease那一個?

如果我明白它的正確性,由於「navigationitem」是一個屬性,它會保留該對象並照顧它。數組保留了所有添加到它的對象。所以一切都應該沒問題?

感謝您的幫助

回答

3

你需要一個一個autorelease發送到UIBarButton,否則你就會有泄漏。

當你alloc它,它有一個「保留計數」爲+1;當你將它添加到數組時,它會到+2。你需要它回到+1,這樣唯一的所有者將是數組,並且當數組被釋放時,UIBarButton將被釋放。你可以這樣做有兩種方式:

[items addObject:[[[UIBarButtonItem alloc] 
       initWithTitle:@"Login" 
       style:UIBarButtonItemStyleBordered 
       target:self 
       action:@selector(tryUserInput)] autorelease]]; 

UIBarButtonItem *item = [[UIBarButtonItem alloc] 
       initWithTitle:@"Login" 
       style:UIBarButtonItemStyleBordered 
       target:self 
       action:@selector(tryUserInput)]; 
[items addObject:item]; 
[item release]; 
+0

[這裏](http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/MemoryMgmt/Articles /MemoryMgmt.html)是關於Cocoa內存管理的文檔;一定要閱讀它,因爲它是基本的 - 而且很清楚。 –