swift 在viewDidAppear方法中,视图的窗口字段为nil?

bqf10yzr  于 2023-05-27  发布在  Swift
关注(0)|答案(1)|浏览(97)

我有几个NSViewControllers引用视图的NSWindowController的字段。我对视图生命周期契约的理解表明,我可以依赖于在调用viewDidAppear时填充的视图窗口。直到今天明显的Xcode更新(当我开始Xcode时,它似乎更新了一些库,现在是9.0版本(9A 235))。现在,当在我的NSViewController示例上调用viewDidAppear时,self.view.window字段实际上是nil!代码看起来像这样(添加了一些调试内容):

override func viewDidAppear() {
    super.viewDidAppear()
    if let w = self.view.window {
        if let bmw = w.windowController {
            rf = (bmw as! BudgetMunkyWindow).refreshManager;
            rf.add(listener:self);
        } else {
            print("There was not window controller");
        }
    } else {
        print("there is no window");
    }
    self.categoryTable.reloadData()
    categoryTable.expandItem(nil, expandChildren:true)
}

这份合同在最近的某个时候发生了变化吗?此时,在视图构造过程中的任何时候都不能访问窗口控制器,这至少可以说是很尴尬的。

g0czyy6m

g0czyy6m1#

这里是一个工作从我的应用程序,包括一些调试代码。从viewDidAppear调用func后,需要1-2次迭代才能跳出循环

var mainWindowTrialCount: Int = 0

func setWindowTitle() {
if let window = NSApplication.shared.mainWindow {
  mainWindowTrialCount = 0
  var titleString = toggleSimulationConfigurationButton.title + ", " + selectedComputeGPUButton.title
  if selectedComputeGPUButton.title != "Compute: CPU" {
    titleString.append(", " + asyncSyncComputeButton.title)
  }
  window.title = titleString
  print(titleString)
} else if mainWindowTrialCount < 10 {
  //work around for window not being valid at viewDidAppear
  DispatchQueue.main.asyncAfter(deadline: .now() + 0.01) {
    self.mainWindowTrialCount += 1
    let elaspedTime: Float = Float(self.mainWindowTrialCount) * 0.01
    print("Initialization time = \(elaspedTime)")
    self.setWindowTitle()
  }
}

}

相关问题