You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

绑定NSTreeController的NSOutlineView点击展开按钮如何获取对应节点?

问题根因

你触发崩溃的核心原因是对outlineViewItemDidExpand通知的参数解析逻辑存在两处错误:

  • notification.userInfo本身是[AnyHashable: Any]类型的字典,直接强转为自定义Node类型会因为类型不匹配触发崩溃
  • 系统存储展开节点的字典key是NSOutlineViewItemKey,不是你填写的"NSObject",取值key错误也会导致类型强转失败
修复代码

因为你使用了NSTreeController做绑定,默认返回的节点是NSTreeNode类型,需要取它的representedObject属性拿到你自定义的业务Node,正确实现如下:

func outlineViewItemDidExpand(_ notification: Notification) {
    guard let userInfo = notification.userInfo,
          let treeNode = userInfo[NSOutlineViewItemKey] as? NSTreeNode,
          let targetNode = treeNode.representedObject as? Node else {
        return
    }
    // 此处targetNode就是你需要的当前展开对应节点
    print("展开节点信息:", targetNode)
}
额外注意事项
  • 请确保你已经将NSOutlineView的delegate设置为当前实现该方法的对象,否则代理方法不会被触发
  • 如果你没有使用NSTreeNode包装自定义节点,可以直接将userInfo[NSOutlineViewItemKey]取出的对象强转为你的自定义Node类型

报错界面截图

内容的提问来源于stack exchange,提问作者user14861636

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 00:45:04