programmatically loading object from subclass of NSView from nib

后端 未结 5 818
闹比i
闹比i 2020-12-24 02:56

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

5条回答
  •  情书的邮戳
    2020-12-24 03:35

    Note that a nib file contains:

    • One or more top-level objects. For example, an instance of MyView;
    • A file’s owner placeholder. This is an object that exists prior to the nib file being loaded. Since it exists before the nib file is loaded, it cannot be the same as the view in the nib file.

    Scenario 1: NSNib

    Let’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.

    Scenario 2: NSViewController

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

提交回复
热议问题