Rizon
Rizon

Reputation: 1546

UIImageView weird image property issue

I'm dealing with a super easy task that somehow introducing some difficulties...

All I'm trying to do is to create a view controller and set its UIImageView's image property to some image. When I try to that, I get nil =\

GenericViewController *genericViewController = [[GenericViewController alloc] init];
UIImage *image = [UIImage imageNamed:@"Camera.png"];
genericViewController.genericImageView.image = image;
NSLog(@"%@", genericViewController.genericImageView.image);

Output: (null)

Upvotes: 0

Views: 197

Answers (1)

Lily Ballard
Lily Ballard

Reputation: 185671

I imagine genericImageView is set up either in a nib or in the -loadView method. However, at the point in which you're trying to access the image view, the view for the VC hasn't been loaded yet. The quick fix is to call

(void)genericViewController.view;

before accessing genericImageView. This will force the view to load. The "better" approach would be to give genericViewController an image property that you assign to, then in its setter you can say

- (void)setGenericImage:(UIImage *)image {
    if (_genericImage != image) {
        [_genericImage release];
        _genericImage = [image retain];
        if ([self isViewLoaded]) {
            self.genericImageView.image = image;
        }
    }
}

and in -viewDidLoad you can say

- (void)viewDidLoad {
    [super viewDidLoad];
    self.genericImageView.image = self.genericImage;
}

This method, besides being more modular and architecturally-sound, also has the advantage where if the view controller's view is unloaded (say, another view is pushed onto the nav stack and a memory warning comes along), when it gets re-loaded it will still have the image.

Upvotes: 1

Related Questions