J W
J W

Reputation: 878

UIImageView alloc] initWithImage using IBOutlet not working

I've typically followed the pattern of creating an object in my method (like viewDidLoad), have the property hold onto it, then release the original object created. So something like this:

NSArray *myArray = [NSArray alloc] initWithObjects:@"1", @"2", @"3", nil];
self.array = myArray;
[myArray release];

I thought I could do the same thing with UIImageView. I have a UIImageView created in my .xib. I have an outlet to it that is a property like so

@property (nonatomic, retain) IBOutlet UIImageView *imageView;

In my viewDidLoad, I do:

UIImageView *imgView = [[UIImageView alloc] initWithImage;[UIImage imageNamed:@"arrow.png"]];
self.imageView = imgView;
[imgView release];

If I run this, I do not get anything on screen. However, if I do just this in my viewDidLoad instead:

[self.imageView setImage:[UIImage imageNamed:@"arrow.png"]];

I do get my arrow image on screen. Is there something different about UIImageView that I am missing here?

Edit because of first response: Is UIImageView different than UITableView in that I need to add it as a subview to my current view? When I create a UITableView in IB, I do not add it as a subview in viewDidLoad.

Thanks.

Upvotes: 1

Views: 5970

Answers (2)

NSIntegerMax
NSIntegerMax

Reputation: 542

You are missing the point behind how IBOutlet work. If something is specified in .xib then it is already allocated for you :) You just use it.

Hence [self.imageView setImage:[UIImage imageNamed:@"arrow.png"]]; works since you just assigned an image to it.

However, when doing

UIImageView *imgView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"arrow.png"]];
self.imageView = imgView;
[imgView release];

you actually deallocated the imageView instance created by IB at the self.imageView = imgView; line and set a new one and neither did you added it as subview to anything. Since it is a new instance it will need to be added !! But anyways this approach is wrong if you are using IBOutlet

Upvotes: 5

Sonny Saluja
Sonny Saluja

Reputation: 7287

You need to add self.imageView to your view hierarchy.

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.imageView = ...

    // You are missing this part!
    [self.view addSubview:self.imageView];

    ...
}

PS. You dont need to mark your UIImageView property as IBOutlet since you are not using Interface Builder to build your view.

Upvotes: 0

Related Questions