Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IBOutlet is nil inside custom UIView (Using STORYBOARD)

I have a custom UIView class. Inside it I have declared an IBOutlet property for UIImageView.

#import <UIKit/UIKit.h>

@interface SettingItem : UIView{

}

@property (strong, nonatomic) IBOutlet UIImageView *myImage;

@end

Now i am using storyboard. There is a viewcontroller. I dragged UIView to viewcontroller. I dragged one UIImageView as a subview of above UIView. I set the "SettingItem" class to UIView from storyboard. I connected the outlet to myImage by normal dragging from outlets of SettingItem from utilities window.


SettingItem implementation

#import "SettingItem.h"

@implementation SettingItem

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
        [self baseInit];
    }
    return self;
}

-(id) initWithCoder:(NSCoder *)aDecoder{
    self = [super initWithCoder:aDecoder];
    if (self) {
        // Initialization code
        [self baseInit];
    }
    return self;
}

- (void) baseInit{
    NSLog(@"myImage %@"self.myImage);
}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect
{
    // Drawing code
}
*/

@end

Now my problem is myImage is always nil, above NSLog just print (null) for the outlet. I checked the view in storyboard and checked its outlet reference and its pointing to myImage. I am missing something. I googled for the help but couldn't find any solution.

Can you please point out what am i doing wrong ?

like image 292
padam thapa Avatar asked Dec 30 '12 08:12

padam thapa


3 Answers

Override awakeFromNib in your view - this is the first lifecycle method to be called after the IBOutlets have been assigned and is the right place for your code.

like image 64
Oly Dungey Avatar answered Nov 05 '22 21:11

Oly Dungey


initialize them in awakeFromNib:

- (void)awakeFromNib
{
    //init code
}
like image 4
inix Avatar answered Nov 05 '22 23:11

inix


I just had the exact same problem and the solution is really easy:

You're accessing myImage to soon - that's it.

Withing -(id) initWithCoder:(NSCoder *)aDecoder{ and - (id)initWithFrame:(CGRect)frame the UIView is not already drawed. So myImage is not initalized yet.

You can test it if you add a UIButton and an IBAction and do something like this:

- (IBAction)buttonClicked:(id)sender {
    NSLog(@"%@",myImage);
}

And you'll see how myImage is not nil anymore.

like image 2
Fabio Poloni Avatar answered Nov 05 '22 21:11

Fabio Poloni