3

尝试将通过连接绑定到属性 (optionSegment) 的选定段NSToolbarItem设置NSSegmentedControl。这样子类化窗口控制器

class MyWindow: NSWindowController {
    dynamic var optionSegment: Int = 0

    override func windowDidLoad() {
        super.windowDidLoad()
    }
}

或者,将 optionSegment 属性放在NSDocument子类中并绑定到该子类。每个作品。问题是,有了这个绑定,或者看似任何对 的绑定NSToolbarItem,我的任何对象(视图、视图控制器、文档等)都不会取消初始化。有了绑定,他们就没有。删除绑定,他们这样做。

任何想法为什么会这样?建议?好难过。

谢谢!

4

2 回答 2

2

正如 Willeke 所建议的,toolbarItem.view 是通往成功的道路。不得不说对象的层次结构对我来说并不总是很清楚,但是当我在一夜之间查看工具栏项挂钩时,.view 似乎是唯一的可能性,Willeke 的建议证实了这一点。Apple 关于绑定的文档确实提到我们有责任解除绑定某些对象,同时解除绑定其他对象。这是我在我的 NSDocument 子类中用于解除绑定的代码,并且视图控制器现在正在取消初始化。

func windowWillClose(notification: NSNotification) {
    let wcs = self.windowControllers
    if wcs.count == 0 { return }
    let wc = wcs[0]
    let toolbar = wc.window?.toolbar
    if toolbar != nil {
        let items = toolbar!.items
        for item in items {
            let v = item.view
            if v != nil {
                // print(v?.className)
                let objects = v!.exposedBindings
                for object in objects {
                    // print(object + " " + item.label + " " + v!.className)
                    v!.unbind(object)
                }
            }
        }
    }
}

这是我遇到的最令人困惑的概念之一 - 如此多的活动部件 - 并且感谢 Willeke 和 stevesliva 的对话,最终找到了解决方案。

从 NSObject(NSKeyValueBindingCreation):

AppKit 对象(视图、单元格、表格列、控制器)上的所有标准绑定在它们被释放时会自动解除绑定,但是如果您为其他类型的对象创建键值绑定,则需要确保在之前删除这些绑定释放(被观察对象对其观察者的引用很弱,因此控制器/模型对象可能会继续引用和传递绑定到它们的对象)。

于 2016-04-21T16:53:29.523 回答
0

由于绑定到其自定义属性,我的窗口控制器尚未取消初始化。在我的情况下,不仅窗口的工具栏视图,而且触摸栏视图也需要解除绑定。感谢大家对这个问题的发现和建议!我正在分享我的片段。

WindowController 实例是窗口的委托。为了简洁起见,NSView 和 NSTouchBar 的扩展。

extension WindowController: NSWindowDelegate {

    func windowWillClose(_ notification: Notification) {
        window?.toolbar?.items.forEach { $0.view?.unbindExposed() }
        if #available(macOS 10.12.2, *) {
            touchBar?.items.forEach { $0.view?.unbindExposed() }
        }
    }

}
extension NSView {

    /// Removes exposed binding between the receiver and a controller.
    func unbindExposed() {
        for binding in exposedBindings {
            unbind(binding)
        }
    }

}
@available(macOS 10.12.2, *)
extension NSTouchBar {

    /// The read-only list of items for the bar, as currently configured by the user.
    var items: [NSTouchBarItem] {
        itemIdentifiers.compactMap { item(forIdentifier: $0) }
    }

}
于 2020-03-09T20:19:23.907 回答