2016-10-26 78 views
0

如何從Xib載入NSView?如何使用Swift從Xib載入NSView 3

我的代碼:

var topLevelArray: NSArray? = nil 
let outputValue = AutoreleasingUnsafeMutablePointer<NSArray>(&topLevelArray) 

if Bundle.main.loadNibNamed("RadioPlayerView", owner: nil, topLevelObjects: outputValue) { 
    let views = outputValue.pointee 
    return views.firstObject as! RadioPlayerView 
} 

topLevelArray = nil 
return nil 

的問題是「outputValue」是一個自動釋放指針,只要我從功能,程序崩潰與ACCESS_BAD_ADDRESS

+0

保持很強的參考使用一個類屬性,然後它會不會被釋放。並嘗試更好地理解ARC和內存管理。 – Volker

+0

是的,的確如此。但我不想保留一個強有力的參考,我只想加載視圖並完成。其實,我已經解決了這些問題。這是相當簡單的,只是刪除指針變量: 讓outputValue = AutoreleasingUnsafeMutablePointer (topLevelArray) ,只是 Bundle.main.loadNibNamed( 「RadioPlayerView」,店主:無,topLevelObjects:topLevelArray) –

回答

1

我做了一個協議返回和延伸要做到這一點:

import Cocoa 

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 
    } 
} 

用法:

final class MyView: NSView, NibLoadable { 
    // ... 
} 

// ...別的地方:

let myView: MyView? = MyView.createFromNib()