macoscocoansviewinitwithcoderinitwithframe

InitWithCoder never called for Cocoa NSView based class


I create a XIB.

I create this class called MyCustomView and assign it to the XIB's File Owner.

- (instancetype)initWithCoder:(NSCoder *)aDecoder{
  self = [super initWithCoder:aDecoder];
  if (self) [self load];
  return self;
}

- (instancetype)initWithFrame:(CGRect)frame {
  self = [super initWithFrame:frame];
  if (self) [self load];
  return self;
}

- (void)load {

  NSArray* topLevelObjects;
  [[NSBundle mainBundle] loadNibNamed:@"MyCustomView"
                                owner:self
                      topLevelObjects:&topLevelObjects];

  NSView* view;
  for (id aView in topLevelObjects) {
    if ([umaVista isKindOfClass:[NSView class]]) {
      view = umaVista;
      break;
    }
  }

  [self addSubview:view];
  view.frame = self.bounds;  

}

I create a NSView on the main app.

I change that view to the MyCustomView.

I run the app. MyCustomView's initWithCoder does not run. initWithFrame does not run. awakeFromNib does not run.

Nothing happens.

Any ideas?


Solution

  • "File's Owner" as I've written elsewhere, isn't a real object in the archive. It's a placeholder. When you unpack the nib, a pre-existing object gets used.

    It looks like you should just be putting an instance of your custom view into the nib. Don't make it File's Owner, just drag a view out from the object palette and then change its class in the Identity Inspector (right pane, top; press ⌘-⌥-3). Build the subviews in the nib too.

    Then get your NSBundle to load the nib for you. Your custom view will get initWithCoder: and awakeFromNib, and you won't have to grovel through the hierarchy to find a particular subview.