如何从 OS X 上的框架实例化 NSViewController(即获取正确的包)

How to instantiate NSViewController from a Framework on OS X (i.e. getting the correct bundle)

我如何从添加到我的 OS X 应用程序 的框架实例化视图控制器(这实际上可能与 iOS 相同的过程,我不确定,最后有一次我查看 iOS 上不允许的框架,但可能已经更改)?

设置如下:

什么不起作用

CustomViewController(nibName: "CustomViewController", bundle:nil) 将无法工作,因为资源 不在 应用程序的主包中(它们在框架中)。

什么有效

要使用以下代码从我的应用程序框架实例化视图控制器(有效!),它使用 NSBundle.allFrameworks() 遍历所有加载的框架并通过比较 bundleIdentifier

func findMyFrameworkBundle() -> NSBundle? {
    if let frameworkBundles = NSBundle.allFrameworks() as? [NSBundle] {
        for bundle in frameworkBundles {
            if let identifier = bundle.bundleIdentifier {
                if identifier == "com.Me.MyFramework" {
                    return bundle
                }
            }
        }
    }
    return nil
}

let nibName = "CustomViewController"
let bundle = findMyFrameworkBundle()
let viewController = CustomViewController(nibName:nibName, bundle:bundle)

如何改善?

这似乎过于复杂,让我觉得我一定做错了什么。一些可能的解决方案:

  1. 我可以更改我的框架并提供始终使用正确的包实例化视图控制器的自定义初始化程序吗?

例如,

class CustomViewController : NSViewController {

    init() {

        let bundle = // ... the correct bundle even when used as an embedded framework in an App
        super.init(nibName: "CustomViewController", bundle: bundle)
    }

    // ... other code
}
  1. 有没有比搜索 NSBundle.allFrameworks() 更好的方法在我的应用程序中提供正确的捆绑包?

我可能误解了你的问题,但我认为标准做法是使用 NSBundle 构造函数,该构造函数将标识符作为其唯一参数。如:

let bundle = NSBundle(identifier: "com.Me.MyFramework")!