Ollie
Ollie

Reputation: 301

Correctly releasing returned UIImage

I call the following method to get an image which I display in a UIImageView. When I am done with the UIImageView I release myImageView.image. I am happy with how I do this but Instruments is showing a leak of UIImage. How should I be releasing the below instance of UIImage?

-(UIImage *)getImageWithRef:(NSString *)ref {
    UIImage *myImage = [[UIImage alloc] initWithContentsOfFile:[NSString stringWithFormat:@"foobar_%@",ref]];
    if (myImage == nil) {
        myImage = [[UIImage alloc] initWithContentsOfFile:@"foobar_defaultImage"];
    }
    return myImage;
}

Thanks in advance

Upvotes: 1

Views: 121

Answers (1)

Divyu
Divyu

Reputation: 1313

Try using auto-release when you return your image.

-(UIImage *)getImageWithRef:(NSString *)ref {
    UIImage *myImage = [[UIImage alloc] initWithContentsOfFile:[NSString stringWithFormat:@"foobar_%@",ref]];
    if (myImage == nil) {
        myImage = [[UIImage alloc] initWithContentsOfFile:@"foobar_defaultImage"];
    }
    return [myImage autorelease];
}

Upvotes: 2

Related Questions