分配时分配对象

Posted

技术标签:

【中文标题】分配时分配对象【英文标题】:allocing object when assigning 【发布时间】:2011-08-19 08:45:54 【问题描述】:

我对 objc 真的很陌生,我正在尝试尽可能多地理解并在内存管理方面获得良好的例程。

我的问题是这样的代码是否危险(我喜欢短代码)

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 = [[UIBarButtonItem alloc] initWithTitle:@"注销" 样式:UIBarButtonItemStyleDone 目标:无 行动:无];

或者我应该在那个上附加一个自动释放?

如果我理解正确的话,因为“navigationitem”是一个属性,它会保留对象并处理它。并且该数组保留了我添加到其中的所有对象。所以一切都应该没问题吗?

感谢您的帮助

【问题讨论】:

【参考方案1】:

您需要向 UIBarButton 发送 autorelease,否则您会发生泄漏。

当你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];

【讨论】:

Here 是关于 Cocoa 内存管理的文档;请务必阅读它,因为它是基本的 - 并且相当清晰。

以上是关于分配时分配对象的主要内容,如果未能解决你的问题,请参考以下文章

java中的全局变量和静态变量是在编译时分配内存还是在加载时分配内存??

如何在运行时分配多维数组?

OutOfMemoryError:分页响应时分配失败

何时为 C++ 中的类的成员函数分配内存空间?

动态内存&对象

按下 UILabel 时分配变量值以打开 Apple 地图