Search code examples
xcodecocoaswiftnibnsbundle

How do you obtain a view from a nib within a playground?


In a typical Xcode project, you can obtain a view from a nib like this:

    var objects: NSArray?;
    NSBundle.mainBundle().loadNibNamed("ExampleView", owner: nil,
                                       topLevelObjects: &objects)
    var view :NSView
    for obj in objects! {
        if (obj.isMemberOfClass(NSView)) {
            view = obj as NSView
        }
    }
    // view is now the NSView object obtained from the nib. Yay.

However, if I create a playground within the same Xcode project and attempt to obtain the view, the above code fails. In fact, loadNibNamed:owner:topLevelObjects: returns false, and we know that loading the nib failed.

Even if I create a standalone playground, and place the .xib file inside the Resources directory, loadNibNamed:owner:topLevelObjects: still returns false.

Why can't I use loadNibNamed:owner:topLevelObjects: to access a nib file from within a playground? What is the correct way to do this?


Solution

  • The mistake I have made is placing the .xib, and not the .nib, in the Resources directory. Once I place the correct file (the .nib file, durp) in the Resources directory, I can indeed access the view.