UIImage解除分配问题

时间:2010-09-15 05:33:47

标签: iphone xcode iphone-sdk-3.0

我一直在解决这个问题,我已经阅读了关于解除分配问题的所有帖子,但无法理解为什么,因为我对Objective-c和iphone很新,正如你所知道的那样:)

但是我不明白的是下面这段代码说我已经过度分配了UIImage,现在我已经尝试了一切,但应用程序仍然崩溃

UIImage *imageSave      = [UIImage imageNamed:@"btn_save.png"];
UIButton *btnSave       = [UIButton buttonWithType:UIButtonTypeCustom];

[btnSave setBackgroundImage:imageSave forState:UIControlStateNormal];

btnSave.frame = CGRectMake(0, 0, imageSave.size.width, imageSave.size.height);

[btnSave addTarget:self action:@selector(save) forControlEvents:UIControlEventTouchUpInside];

UIBarButtonItem *barBtnSave = [[UIBarButtonItem alloc] initWithCustomView:btnSave];

self.navigationItem.rightBarButtonItem  = barBtnSave;

//[imageSave release];
//[btnSave release];
[barBtnSave release];


UIImage *imageCancel    = [UIImage imageNamed:@"btn_cancel.png"];
UIButton *btnCancel     = [UIButton buttonWithType:UIButtonTypeCustom];

[btnCancel setBackgroundImage:imageCancel forState:UIControlStateNormal];

btnCancel.frame = CGRectMake(0, 0, imageCancel.size.width, imageCancel.size.height);

[btnCancel addTarget:self action:@selector(cancel) forControlEvents:UIControlEventTouchUpInside];
UIBarButtonItem *barBtnCancel = [[UIBarButtonItem alloc] initWithCustomView:btnCancel];

self.navigationItem.leftBarButtonItem   = barBtnCancel;

//[imageCancel release];
//[btnCancel release];
[barBtnCancel release];

1 个答案:

答案 0 :(得分:1)

好的,我们来看看这两行:

UIImage *imageCancel = [UIImage imageNamed:@"btn_cancel.png"];

[imageCancel release];

在1行中,您创建了一个 autorelease 图像,然后retainCount将为0.然后,您释放图像,这将使retainCount为-1​​,从而导致崩溃

您需要记住的是增加retainCount的列表:alloccopyretain ...如果您将这些方法之一调用到某个对象,则必须执行:autoreleaserelease