Would such assignment of image cause a memory leak

2019-08-11 08:19发布

问题:

- (void)viewDidLoad {
    [super viewDidLoad];
    landscape.image = [UIImage imageNamed:@"tenerife1.png"];
}

I assign a new UIImage to the image property of an UIImageView object. I am not sure if that would result in a memory leak?

回答1:

No, it should not. The old image should be automatically released when you set the new one, and the "imageNamed" method uses autorelease, so you should be OK there.



回答2:

hey take into account imageNamed has serious memory issues as you loose control over its cache - ie: once you are done with your image, you cannot reclaim that memory. a quick google search would let you know how many people have faced problems with imageNamed

i was at the apple iphone tech talks and the guy giving the presentation confirmed the same damn thing - he suggested using imageWithContentsOfFile instead of imageNamed

if you just have couple of small images, its fine otherwise use imageWithContentsOfFile even though its a bit slower - and implement your own caching logic - check this great link on how to do it here



回答3:

It depends on how the image property is defined. If it's defined as retain or, I suppose, even copy, it should be fine. You'll end up trying to reference deallocated memory and crashing your program if it's defined as assign.



回答4:

Not ordinarily, but it would depend on how you've defined landscape.image. See post above. Be careful with using a lot of these:

[UIImage imageNamed:@"tenerife1.png"];

Since there is a tendency for these images to fill up memory, without getting released.