J T
J T

Reputation: 337

UIImageView subclass duplicate the image

I am working on a subclass of UIImageView and one of the things I require is when the object is initalised with the initWithImage: message a 'copy' is created.

I must be confusing something because I can't see what is not working here..

- (id)initWithImage:(UIImage *)image {
[image retain];
if (self = [super initWithImage:image]) {

    if (!maskImage) {
        maskImage = [UIImage imageWithCGImage:[image CGImage]];
        if (maskImage != nil) {
            NSLog(@"Made mask image");
        } else {
            NSLog(@"Failed");
        }
        //maskImage = [UIImage imageNamed:@"image.png"];
    }
}

[image release];
return self;
}

There are no errors when I build this and the maskimage does appear to be created (i do not get the failure message). However, if I uncomment the line allocating from a png it works.

What am I missing?

Thanks!

Upvotes: 1

Views: 4273

Answers (3)

Valerii Hiora
Valerii Hiora

Reputation: 1552

You should retain created image, in example like this:

- (id)initWithImage:(UIImage *)image {
    if (self = [super initWithImage:image]) {
        if (!maskImage) {
                maskImage = [[UIImage imageWithCGImage:[image CGImage]] retain];
                if (maskImage != nil) {                
                        NSLog(@"Made mask image");
                } else {
                        NSLog(@"Failed");
                }
        }
    }
    return self;
}

Upvotes: 1

Corey Floyd
Corey Floyd

Reputation: 25969

First, you should set maskImage to nil, to make sure it isn't garbage:

self.maskImage=nil;

That may screwing up your line (if not now, then later):

if(!imaskImage)

Then, to make a copy, just implement NSCopying in a UIImage subclass. It's easy to do. Then you can type:

maskImage = [image copy];

Alternatively, you can convert the image to data, archive, then unarchive, then convert back to a UIImage. This gives you a complete copy of the image. It's a little more complex, but its the same method used for making deep copies of an object graph.

Upvotes: 0

Jordan
Jordan

Reputation: 21760

Try this. Should work.

- (id)initWithImage:(NSString *)image {
if (self = [super initWithImage:image]) {

        if (!maskImage) {
                img = [UIImage imageNamed:image];
                maskImage = CGImageRetain(img.CGImage);
                if (maskImage != nil) {
                        NSLog(@"Made mask image");
                } else {
                        NSLog(@"Failed");
                }
        }
}

return self;
}
  1. Changes
    • pass NSString instead of image
    • no need to retain/release image
    • need to define img, maskImage in .h
    • maskImage in .h should have retain property set in @property ( e.g. @property (nonatomic, retain))

Upvotes: 0

Related Questions