2011-08-19 164 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内存管理的文档;一定要阅读它,因为它是基本的 - 而且很清楚。 –