折旧的NSNibLoading方法的替换(loadNibFile:,loadNibNamed:等)?

时间:2012-10-07 10:06:04

标签: objective-c xcode macos cocoa appkit

我发现NSBundle中的NSNibLoading方法:

+[NSBundle loadNibFile:externalNameTable:withZone:]
+[NSBundle loadNibNamed:owner:]
-[NSBundle loadNibFile:externalNameTable:withZone:]

在10.8中被标记为已弃用 - 在10.8及更高版本中加载笔尖的正确方法是什么?

我正在尝试在我的应用中创建自定义工作表,是否必须使用NSWindowController为自定义工作表创建initWithWindowNibName

2 个答案:

答案 0 :(得分:13)

如果您的应用支持Lion,那么loadNibNamed:owner:topLevelObjects:将不会触发,并且在Lion上运行时您将获得异常(无法识别的选择器)。经过一番搜索,我想出了这个:

    // loadNibNamed:owner:topLevelObjects was introduced in 10.8 (Mountain Lion).
    // In order to support Lion and Mountain Lion +, we need to see which OS we're
    // on. We do this by testing to see if [NSBundle mainBundle] responds to
    // loadNibNamed:owner:topLevelObjects: ... If so, the app is running on at least
    // Mountain Lion... If not, then the app is running on Lion so we fall back to the
    // the older loadNibNamed:owner: method. If your app does not support Lion, then
    // you can go with strictly the newer one and not deal with the if/else conditional.

    if ([[NSBundle mainBundle] respondsToSelector:@selector(loadNibNamed:owner:topLevelObjects:)]) {
        // We're running on Mountain Lion or higher
        [[NSBundle mainBundle] loadNibNamed:@"NibName"
                                      owner:self
                            topLevelObjects:nil];
    } else {
        // We're running on Lion
        [NSBundle loadNibNamed:@"NibName"
                         owner:self];
    }

如果你真的想使用{Lion} +的topLevelObjects:&array,并且你也想支持Lion,看起来你需要回到loadNibFile:externalNameTable:withZone :(同时作为一个类和针对Lion条件的实例方法(我可能错了)。我得到的印象是创建了loadNibNamed:owner:topLevelObjects:来替换它。

我还在其他地方读到,当使用较新的loadNibNamed:owner:topLevelObjects:作为工作表时,您应取消选中工作表(窗口)的“释放时关闭”。关闭工作表时应该注意这一点:

[self.sheet close];
self.sheet = nil;

如果您要打开非模态窗口,我不确定应该对该复选框做些什么。有什么想法吗?

答案 1 :(得分:6)

OS X v10.8中不推荐使用NSBundle类方法loadNibNamed:owner: loadNibNamed:owner:topLevelObjects: ,评论in the documentation说明原因:

  

与遗留方法不同,对象遵循标准的可可内存管理规则;有必要通过使用IBOutlets或保持对数组的引用来保持对它们的强引用,以防止取消分配nib内容。