Search code examples
iphoneobjective-cuiviewsubclassing

iPhone - Load a UIView from a nib file?


I am subclassing UIView trying to load the view i have dropped in interface builder from a nib file. I get the following error on the return line:

Terminating app due to uncaught exception 'NSGenericException', reason: 'This coder requires that replaced objects be returned from initWithCoder:'

- (id)initWithCoder:(NSCoder *)aDecoder
{
    [super initWithCoder:aDecoder];
    NSArray *objects = [[NSBundle mainBundle]
                        loadNibNamed:@"MyView" 
                        owner:nil 
                        options:nil];
    if (self = [objects objectAtIndex:0])
    {
    }
    return [self retain];
}

Solution

  • You are doing something very strange)

    loadNibNamed:owner:options: will call initWithCoder: to instantiate your view from xib. But you are calling loadNibNamed:owner:options: from initWithCoder:. Infinite recursion?

    To load view from xib you can do the next:

    @implementation MyView
    
    + (MyView*) myView
    {
      NSArray* array = [[NSBundle mainBundle] loadNibNamed:@"MyView" owner:nil options:nil];
      return [array objectAtIndex:0]; // assume that MyView is the only object in the xib
    }
    
    @end