(iphone) UIImageView setImage: leaks?
i'm changing image of UIImageview by [self setImage: newImage];
Looks like every time I does that with newImage, prior image doesn't seem to be released.
What开发者_JAVA百科's the correct way to replace image of UIImageView?Thank you
Yes, UIImageView setImage does leak! Actually, leaks CGImage, not UIImage (as instrument "allocation" shows)
I use BrutalUIImage instead of UIImage
@interface BrutalUIImageView : UIView {
UIImage *image;
}
@property(nonatomic, retain) UIImage *image;
@end
@implementation BrutalUIImageView
@synthesize image;
- (void)setImage:(UIImage *)anImage {
[image autorelease];
image = [anImage retain];
[self setNeedsDisplay];
}
- (void)drawRect:(CGRect)rect {
[super drawRect:rect];
[image drawInRect:rect];
}
- (void)dealloc {
[image release];
[super dealloc];
}
@end
UIImageView setImage:
never leaks, unless the image you are passing doesn't get released.
Your code wont leak, if your are assigning an autoreleased image to the image view, something like the following.
UIImage *newImage = [UIImage imageNamed:@"sampleImage"];
[yourImageView setImage:newImage];
But, if you are allocating the image somewhere, you have to release it manually.
Your BrutalUIImageVIew class is really interesting, but by drawing the Image using UIImage "drawInRect:" method, i loss the transparent areas of my PNG file.
Do you know how to draw the image, keeping the PNG transparence ? (Of course, not using UIImageVIew wich leaks the CGImage while calling "setImage:")
Yes UIImageView setImage indeed leaks!
If you cycle through a bunch of images with
[yourImageView setImage:[UIImage imageNamed:@"sampleImage.png"]];
you can see on instruments memory usage increasing. This seems to be some kind of caching going around since after cycling through all the images memory usage will go flat.
The correct, or at least, the non leaky way to do it is:
NSString *thePath = [[NSBundle mainBundle] pathForResource:@"sampleImage" ofType:@"png"];
UIImage *newImage = [[UIImage alloc] initWithContentsOfFile:thePath];
[yourImageView setImage:newImage];
I verified this on my code as my APP was cycling through a lot of large image files.
精彩评论