开发者

Memory handling on re-assignment

How does the memory management work for e.g. a UIImage which is reassigned to another image.

e.g.

someImage = image1.png

someImage = image2.png

What happens to image1.png in terms of memory? Will there be a leak on the reassignment?

The images will be loaded from t开发者_开发知识库he documents directory.


It depends on how you loading the image. Just like with any other objects, if you alloc & init yourself then you have to clean up yourself. Otherwise, you can rely on the autoreleased objects.

This won't leak:

UIImage* someImage;
someImage = [UIImage imageWithContentsOfFile:@"<path>/file1.png"];
// usage the image here ...
someImage = [UIImage imageWithContentsOfFile:@"<path>/file2.png"];
// use the image again ...

This will:

UIImage* someImage;
someImage = [[UIImage alloc] initWithContentsOfFile:@"<path>/file1.png"];
// usage the image here …
someImage = [[UIImage alloc] initWithContentsOfFile:@"<path>/file2.png"];
// use the image again ...

It really remains this simple as long as you stick with the Cocoa classes - and you probably don't need to wander into the Carbon API any more. :)


That depends on how you assign the images.

If you do something like

UIImage *someImage = [[UIImage alloc] initWithContentsOfFile:@"image1.png"];
...
someImage = [[UIImage alloc] initWithContentsOfFile:@"image2.png"];

There will be a memory leak because you have the ownership over someImage and you're not releasing it.

A correct way to do it is:

UIImage *someImage = [[UIImage alloc] initWithContentsOfFile:@"image1.png"];
...
[someImage release];
someImage = [[UIImage alloc] initWithContentsOfFile:@"image2.png"];
...
[someImage release];

Or you can use autoreleased objects

UIImage *someImage = [[[UIImage alloc] initWithContentsOfFile:@"image1.png"] autorelease];
...
someImage = [[[UIImage alloc] initWithContentsOfFile:@"image2.png"] autorelease];


Another way is to use @property with the "retain" attribute set (together with @synthesize). But then you need to "release" an allocated object when you assign them:

@property (retain) UIImage *someImage;
...
@synthesize someImage;
...
self.someImage = givenImageg1;
...
self.someImage = givenImage2;

This last line will release the first image set and then then retain the second one. Please note that you HAVE TO use "self." in order to make sure that you use the setter method which does the magic otherwise nothing will happing.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜