释放分配给UIBar的NSArray

时间:2011-08-30 08:35:51

标签: ios objective-c memory-management nsarray

在我的应用程序中,我想制作数组,添加到工具栏,然后释放它。然而,当我发布它我的应用程序崩溃。为什么这样...?该怎么做才能省略它?

UIImage *button1Image = [UIImage imageNamed:@"button1Image.png"];
cameraToolbar = [[UIToolbar alloc] init]; //declared in .h
UIBarButtonItem *button1 = [[ UIBarButtonItem alloc ] initWithTitle: @"qwerty" style: UIBarButtonItemStyleBordered target: self action: @selector(doAction)];
[button1 setImage:button1Image];
//same method to add flexItem and button2Image

NSArray *items = [NSArray arrayWithObjects: button1, flexItem, button2, nil];
[cameraToolbar setItems:items animated:NO];
self.view = cameraToolbar;

[items release]; // here it crashes, why? How to fix?
[button1 release];
[button2 release];
[flexItem release];
[button1Image release]; // here i get "Incorrect decrement of the reference count 
//of an object that is not owned at this point by the caller"
[button2Image release];

2 个答案:

答案 0 :(得分:0)

[NSArray arrayWithObjects:]是一个类方法,它返回一个自动释放对象的数组.so 你不应该释放它

如果您使用类似alloc,copy,retain创建对象,则只有您有责任释放它们。

NSArray *items=[[NSArray alloc]initWithObjects:button1, flexItem, button2, nil];


............



[items release];

像button1Image object.take care

这样

答案 1 :(得分:0)

button1Image被分配了一个自动释放的对象,因此不应发送释放消息。内存管理基于对象引用计数,当计数变为零时,将释放内存。释放消息将引用计数减1。