NSArray包含两个元素,但myArray [0]为nil?

时间:2019-06-26 12:54:55

标签: ios macos cocoa cocoa-touch nsview

我正在尝试从文件中加载NIB。

我有这个代码,来自here

protocol NibLoadable {
  static var nibName: String? { get }
  static func createFromNib(in bundle: Bundle) -> Self?
}

extension NibLoadable where Self: NSView {

  static var nibName: String? {
    return String(describing: Self.self)
  }

  static func createFromNib(in bundle: Bundle = Bundle.main) -> Self? {
    guard let nibName = nibName else { return nil }
    var topLevelArray: NSArray? = nil
    bundle.loadNibNamed(NSNib.Name(nibName), owner: self, topLevelObjects: &topLevelArray)
    guard let results = topLevelArray else { return nil }
//    let views = Array<Any>(results).filter { $0 is Self }
//    return views.last as? Self
    let element =      results[0] as? Self

    return results[0] as? Self
  }
}

结果包含两个元素:NSView和NSApplication。

这里的问题是element为nil。注释后的代码也给了我nil

我是新手。 Self传递的内容是什么,或者它在createFromNib的最后一行代表什么?

2 个答案:

答案 0 :(得分:1)

不能保证第一个对象是请求的视图。

使用first(where

获得正确的视图

并声明nibName为非必填项。

protocol NibLoadable {
    static var nibName: String { get }
    static func createFromNib(in bundle: Bundle) -> Self?
}

extension NibLoadable where Self: NSView {    
    static var nibName: String {
        return String(describing: Self.self)
    }

    static func createFromNib(in bundle: Bundle = Bundle.main) -> Self? {
        var topLevelArray: NSArray? // Optionals are nil by default
        bundle.loadNibNamed(NSNib.Name(nibName), owner: self, topLevelObjects: &topLevelArray)
        return topLevelArray?.first(where: { $0 is Self }) as? Self
    }
}

答案 1 :(得分:0)

经过数小时的尝试来摆弄不存在的文档,我来了,这要简单得多。

  func loadViewFromNib() {

    var topLevelArray : NSArray?

    let bundle = Bundle(for: type(of: self))
    let nib = NSNib(nibNamed: .init(String(describing: type(of: self))), bundle: bundle)!
    nib.instantiate(withOwner: self, topLevelObjects: &topLevelArray)

    let myView = topLevelArray?.first(where: { $0 is NSView }) as? NSView
    addSubview(myView!)
}

感谢@vadian的所有努力。