IBOutlet isn't connected in awakeFromNib

Sofi Software LLC picture Sofi Software LLC · Aug 2, 2011 · Viewed 15.1k times · Source

The sample code linked here works great and allows a UIScrollView to display images with paging and preview of the images before and after the current image:

I'm trying to encapsulate the example in a single control that can be reused. So I created a PagingScrollView:

@interface PagingScrollView : UIView {
    IBOutlet UIScrollView * scrollView;
}

@property (nonatomic,retain) IBOutlet UIScrollView * scrollView;

@end

with dirt simple implementation

- (void) awakeFromNib
{
    [super awakeFromNib];

    NSLog(@"awake from nib");
}

In PagingScrollView.xib, I put a View containing a UIScrollView and a ARScrollViewEnhancer exactly as in the original ScrollViewPagingExampleViewController xib. Its File's Owner's class is set to PagingScrollView, and its scrollView outlet is set to the child UIScrollView.

In ScrollViewPagingExampleViewController, I simply declare:

IBOutlet PagingScrollView   *pagingScrollView;

And in IB, I drag a View, set its class to PagingScrollView, and hook up its pagingScrollView outlet to the PagingScrollView.

In awakeFromNib, the scrollView property is nil. I would think that since the scrollView is hooked up in IB in the same nib, it would be available by this point.

Confusingly, in ScrollViewPagingExampleViewController.xib, there is an empty outlet named scrollView. This might indicate that there is a different instance of PagingScrollView than the one defined in PagingScrollView.xib.

As a result, I can't populate the UIScrollView with the actual child views. What am I doing wrong here?

Answer

ashack picture ashack · Aug 3, 2011

There is a very good answer to this question here: Accessing View in awakeFromNib?

Long story short, the view may be loaded in awakeFromNib, but its contents are loaded lazily, which is why you should use viewDidLoad instead of awakeFromNib for what you are trying to achieve.