1

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?

Duck
  • 34,902
  • 47
  • 248
  • 470
  • What do you mean by "assign it to the `XIB`'s first responder"? You can't "assign" anything to First Responder, that's a proxy item that represents the dynamic first responder value. – Lily Ballard Sep 05 '17 at 21:33
  • what do you mean? this is how all tutorials on the web tell. – Duck Sep 05 '17 at 21:34
  • Do you mean you assigned it to "File's Owner"? – Lily Ballard Sep 05 '17 at 21:34
  • ah, sorry, I mean File Owner... – Duck Sep 05 '17 at 21:35
  • Closely related (same cause, really): [-awakeFromNib for File's Owner](https://stackoverflow.com/questions/45370300/handling-of-awakefromnib-for-the-object-that-is-files-owner/45373876#45373876) – jscs Sep 05 '17 at 21:38
  • "File's Owner" isn't actually in the archive, it's just a placeholder. – jscs Sep 05 '17 at 21:40
  • so what is the solution for this? Please make it an answer, so I can accept and give you the points and the glory... – Duck Sep 05 '17 at 21:40
  • Add an instance of the view to the nib, and unarchive the nib in the usual way rather than handwriting it. – jscs Sep 05 '17 at 21:42
  • this is klingon to me – Duck Sep 05 '17 at 21:43

1 Answers1

1

"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.

jscs
  • 63,694
  • 13
  • 151
  • 195