分配时分配对象
我对 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 分配] initWithTitle:@"注销" 样式:UIBarButtonItemStyleDone 目标:无 行动:无];
或者我应该在那个上附加一个自动释放?
如果我理解正确的话,因为“navigationitem”是一个属性,它保留该对象并处理它。该数组保留了我添加到其中的所有对象。那么一切都应该没问题吗?
感谢您的帮助
I am really new to objc and I am trying to understand as much as possible and get a good routine when it comes to mem management.
My question is if code like this is dangerous (i love short code)
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];
In the examples I can find people always create the object that they add in the array, add it and then release it. If I alloc it and adds it at the same time, the array will take care of it aye? And I am releasing that when I'm done with it. Also, can I write it like this?
self.navigationItem.backBarButtonItem = [[UIBarButtonItem alloc]
initWithTitle:@"Logout"
style:UIBarButtonItemStyleDone
target:nil
action:nil];
Or should I attach an autorelease on that one?
If I understood it correclty, since the "navigationitem" is a property it retains the object and takes care of it. And the array retains all the objects I add to it. So everything should be fine?
Thanks for your help
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您需要将
autorelease
发送到 UIBarButton,否则就会发生泄漏。当您
分配
它时,它的“保留计数”为+1;当你将它添加到数组时,它会变成+2。您需要它返回到+1,以便唯一的所有者将是数组,并且当数组被释放时,UIBarButton 将被释放。您可以通过两种方式完成此操作:或者
You need an to send an
autorelease
to the UIBarButton, or you'll have a leak.When you
alloc
it, it has a "retain count" of +1; when you add it to the array it goes to +2. You need it to go back to +1, so that the only owner will be the array, and the UIBarButton will be deallocated when the array is freed. You can do it in two ways:or