views:

37

answers:

1

I am creating a UIImage programmatically in my UIView's drawRect function. Is there a way that the UIViewController responsible for this UIView access that image (or a copy of it) for manipulation?

Appreciate any pointers and thanks in advance.

A: 

If your UIImage you create programmatically in your drawrect is stored as a property on the UIView subclass, then the UIViewController can access the image.

Obviously, if you are using Interface Builder you'd need to wire up your UIView subclass to an IBOutlet on the UIViewController class to access the property, but I'm sure you're doing that already.

e.g. in the drawrect function

self.storedImage = [[UIImage alloc] init... ];

in the header for the UIView subclass
UIImage* storedImage;

@property (nonatomic, retain) UIImage* storedImage;

The nonatomic retained property ensures that you're not leaking UIImages each time the draw rect function is called.

Ben Clayton
In your example you are introducing a memory leak with the line...self.storedImage = [[UIImage alloc] init... ];As storedImage is a retain property. Instead you should have...UIImage *newImage = [[UIImage alloc] init... ];self.storedImage = newImage;[newImage release];OR...self.storedImage = [[[UIImage alloc] init... ] autorelease];You'd be surprised how many times I see this! :)
Simon Lee