Kumar
Kumar

Reputation: 5469

How to release background image of UIButton?

Can anyone tell me how to release the image which is used as background image in UIButton. I created Custom button using following code but i could not able to release the memory of UIImage which is set a background image in the UIButton. Here is code which i used to create UIButton

`

   for (int index=0;index<10; index++)

   {            
    UIImage *image=[[UIImage alloc] initWithData:imageData];


    CGRect frame = CGRectMake(xValue, 10, 50, 50);  
    UIButton *button = [[UIButton alloc] initWithFrame:frame];

    [button addTarget:self action:@selector(onClickImgButton:)forControlEvents:UIControlEventTouchUpInside];
    [button setTag:index];      
    [button setContentHorizontalAlignment:UIControlContentHorizontalAlignmentLeft];     
    [button setImage:image forState:UIControlStateNormal];                      
    [button.layer setCornerRadius:10.0f];
    [button.layer setMasksToBounds:YES];
    [button.layer setBorderWidth:3.0f];
    [button.layer setBorderColor:[[UIColor lightGrayColor] CGColor]];

    image=nil;
    [image release];


    [horizontalScrollView addSubview:button];
    button=nil; 
    [button release];


    xValue=xValue+60;
    cx +=60;
}

`

Upvotes: 0

Views: 1237

Answers (2)

Ken
Ken

Reputation: 31161

In the above you're sending the release message to nil. In general reverse this, i.e.

[image release];
image = nil;

A similar mistake was made here.

However, since the UIButton instance is (according to a quick look at UIButton.h) retaining the image it's a mistake to do image = nil i.e. just

[image release];

is correct. You're currently making a big assumption about how a given object sets one of its properties.

For example, imagine what happens when the time comes to deallocating your UIButton instance. How is it ever going to send release to your image, which it was retaining, when you've long since set your image to nil? The button finds itself retaining a nil image. It'll be faced with the same problem you gave yourself -- sending release to nil!

Upvotes: 1

Zaky German
Zaky German

Reputation: 14334

First, you mixed your image=nil; [image release];

order, you should first release, than set the pointer to nil. Right now you're sending "release" to nil and nothing happens. You're doing the same for the button btw.

Now if you want the image to be freed from memory, you can't do it as long as it's being used by the button. So you'll have to either free the button from memory (in this case by fixing the release and setting the pointer to nil, and removing the button from it's superview) or do

[button setImage:nil forState:UIControlStateNormal];

Should set the retain count to 0 and eventually dealloc the image

Upvotes: 2

Related Questions