【问题标题】:Loading a view makes the program crash加载视图会使程序崩溃
【发布时间】:2016-07-20 04:55:08
【问题描述】:

我仍在学习视图的工作原理,但我发现了一个我无法解决的问题... 我得到了类GraficsBalancGlobalViewController这是类GraficViewController的子类

class GraficsBalancGlobalViewController: GraficViewController {
  @IBAction func afegeixGrafic(sender: NSButton) {
    addNewGrafic() // which is set on the GraficViewController
  }
}

当我执行 IBAction afegeixGrafic 时,我的程序在下面标记的行崩溃:

class GraficViewController: NSViewController, GraficViewDataSource {

  @IBAction func button(sender: NSButton) {
    addNewGrafic()
  }

  func addNewGrafic() {
    let frame = NSRect(x: 0, y: 0, width: self.view.bounds.width , height: self.view.bounds.width * 0.25)
    let nouGrafic = GraficView(frame: frame)
    scrollView.addSubview(nouGrafic) <---- BREAK here!
  }

  @IBOutlet weak var scrollView: NSView!
  //...more code
}

编译器说:

致命错误:在展开可选值时意外发现 nil

GraficViewController 中的按钮 (IBAction) 效果很好!!所以我认为问题与scrollView有关,但我不知道可以是什么..它被初始化了..

  • 只是提到GraficView(frame: frame)不是问题,因为我尝试过并且效果很好。

【问题讨论】:

  • 您是否检查了IBOutlet 中的scrollView
  • 在此行添加断点,并在调试器控制台中输入“p scrollView”。 scrollView 是 nil 吗?
  • @Drako 是的!你是对的,scrollView 是 nill,但它存在,它在屏幕上!
  • 我发现在@IBAction func button 的情况下,scrollView 不为零!,我真的不知道为什么.. 执行其他@IBAction 时不起作用...跨度>

标签: xcode swift view viewcontroller fatal-error


【解决方案1】:

我确实相信! 是你的祸根:

@IBOutlet weak var scrollView: NSView!

Xcode 确实会为 IBOutlets 生成带有强制解包 (!) 的条目,但它实际上应该是可选的 (?),因为您无法保证 何时 参考是将被设置。如果你有一些依赖scrollView存在的逻辑,你可以通过依赖didSet来实现:

@IBOutlet weak var scrollView: NSView? {
    didSet {
        guard let sview = scrollView else {
            return // because scrollView is nil for some reason
        }
        // do your scrollView existence dependent logic here (eg. reload content)
    }
}

func addNewGrafic() {
    let frame = NSRect(x: 0, y: 0, width: self.view.bounds.width , height: self.view.bounds.width * 0.25)
    let nouGrafic = GraficView(frame: frame)
    scrollView?.addSubview(nouGrafic)
}

我希望这会有所帮助。

【讨论】:

  • 其实我还没有存在依赖逻辑。使用更改,当我单击@IBAction afegeixGrafic 时,没有在// do your scrollView existence dependent logic here (eg. reload content) 处写任何东西,视图上什么也没有。我想要的是在滚动视图中出现新视图,也许我对此错了..
  • 使用第一个时滚动视图怎么可能为零:@IBAction afegeixGrafic 但使用@IBAction func button时不是'?
  • 没有保证说明这些出口/动作是按一定/可靠的顺序设置的。试试上面的(最近的编辑)
  • 它有帮助,因为程序现在不会崩溃,但视图不会出现。那是因为当我在 @IBAction afegeixGrafic i 中使用它时,scrollView 是空的(nil) '不知道如何解决它。
  • didSetaddNewGrafic中放入调试语句(eg NSLog,因为它打印时间并按顺序打印)以确定事件的顺序。插座也可能连接不正确。
猜你喜欢
  • 1970-01-01
  • 2011-09-09
  • 2012-07-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-09-25
相关资源
最近更新 更多