How do I correctly load an object that is a subclass of NSView using a Xib?
I want it to be loaded dynamically not from the beginning so I made a MyView.Xib From MyD
Note that a nib file contains:
MyView;NSNibLet’s consider that your nib file has only one top-level object whose class is MyView, and the file’s owner class is MyAppDelegate. In that case, considering that the nib file is loaded in an instance method of MyAppDelegate:
NSNib *nib = [[[NSNib alloc] initWithNibNamed:@"MyView" bundle:nil] autorelease];
NSArray *topLevelObjects;
if (! [nib instantiateWithOwner:self topLevelObjects:&topLevelObjects]) // error
MyView *myView = nil;
for (id topLevelObject in topLevelObjects) {
if ([topLevelObject isKindOfClass:[MyView class]) {
myView = topLevelObject;
break;
}
}
// At this point myView is either nil or points to an instance
// of MyView that is owned by this code
It looks like the first argument of -[NSNib instantiateNibWithOwner:topLevelObjects:] can be nil so you wouldn’t have to specify an owner since it seems that you aren’t interested in having one:
if (! [nib instantiateWithOwner:nil topLevelObjects:&topLevelObjects]) // error
Although this works, I wouldn’t rely on it since it’s not documented.
Note that you have ownership of the top level objects, hence you are responsible for releasing them when they’re no longer needed.
NSViewControllerCocoa provides NSViewController to manage views; usually, views loaded from a nib file. You should create a subclass of NSViewController containing whichever outlets are needed. When editing the nib file, set the view outlet and whichever other outlets you may have defined. You should also set the nib file’s owner so that its class is this subclass of NSViewController. Then:
MyViewController *myViewController = [[MyViewController alloc] initWithNibName:@"MyView" bundle:nil];
NSViewController automatically loads the nib file and sets the corresponding outlets when you send it -view. Alternatively, you can force it to load the nib file by sending it -loadView.