我是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 = [[UIBarButtonItem alloc] initWithTitle:@ “注销” 风格:UIBarButtonItemStyleDone 目标:无 动作:无];
或者我应该在那个附加自动释放?
如果我理解它是正确的,因为“navigationitem”是一个属性,它保留了对象并负责处理它。并且数组保留了我添加到它的所有对象。所以一切都应该没问题?
感谢您的帮助
答案 0 :(得分: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];