views:

26

answers:

1

Hi,

i've been pulling my hair over this problem, i've read all the post about deallocation problem but couldnt understand why, because i'm pretty new with objective-c and iphone, as you can tell :)

but what i dont understand is this block of code below saying i've over-deallocated UIImage, now i have tried everything but the app still crashes

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  A: 

Ok, let's take a look at these 2 lines:

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

[imageCancel release];

In 1 line, you create an autorelease image, then the retainCount would be 0. Then, you release the image, which would make the retainCount is -1, causing the crash

What you need to remember is a list of increasing your retainCount: alloc, copy, retain ... If you call one of these methods to an object, you have to do either : autorelease or release

vodkhang
thanks will try that
bebensiganteng