Wicketman
Wicketman

Reputation: 15

Object leak after adding a subview

Fellow developers,

I'm trying to set a web image as a background for a UIButton. Everything works execept when I build and analyze it shows that aImage still has a +1 reference. Adding a release for aImage after addSubview doesn't solve it. I think I might solve it by subclassing and writing a custom dealloc but that feels like a convoluted solution. Does anyone have any suggestions? Thanks !

UIImage *aImage = [[UIImage alloc] initWithData:[NSData dataWithContentsOfURL:mUrl]];
[myOverviewButton setBackgroundImage:aImage forState:UIControlStateNormal];
[aView addSubview:myOverviewButton];

Upvotes: 0

Views: 187

Answers (2)

Ian Henry
Ian Henry

Reputation: 22403

As soon as the code you've shown finishes executing, aImage should have a reference count of 2: one from the alloc call and one from the setBackgroundImage:forState: call. You should release after setBackgroundImage:forState: to balance the alloc, but you will still have a reference count of 1. This is expected -- otherwise myOverviewButton wouldn't have an image to work with. It should go down to 0 when myOverviewButton deallocates.

Upvotes: 0

TomSwift
TomSwift

Reputation: 39512

either add an autorelease to the aImage, or call release on it manually.

UIImage *aImage = [[[UIImage alloc] initWithData:[NSData dataWithContentsOfURL:mUrl]] autorelease];

When you call setBackgroundImage:, the button is performing a retain on the image. When you did the alloc/init you did a retain that was never released.

Upvotes: 1

Related Questions