简体   繁体   English

Swift 4 NSTreeController @objc动态var节点= [Node]()在启动时使应用程序崩溃

[英]Swift 4 NSTreeController @objc dynamic var nodes = [Node]() crashes app on start

After Swift 4 migration, my NSTreeController project now crashes on start. 在Swift 4迁移之后,我的NSTreeController项目现在在启动时崩溃。 I boiled it down to the casting of @objc to my dynamic array. 我将其归结为将@objc转换为动态数组。 Does anyone have any idea why it keeps causing the crash? 有谁知道为什么它继续导致崩溃?

@objc dynamic var nodes =[Node]() // The @objc is causing the crash

I figured out the problem. 我解决了这个问题。 It was when I did the Swift migration to 4 and selected the first option (recommended) which did not attach @objc property to variables that needed it. 这是当我将Swift迁移到4并选择第一个选项(推荐)时,该选项未将@objc属性附加到需要它的变量上。 Mainly my entire Node class needed @objc property on the variables, which the second option 'Match Swift 3 Behavior', did do and my desktop application ran without any crashes. 主要是我的整个Node类都需要变量的@objc属性,第二个选项“ Match Swift 3 Behavior”确实做到了,并且我的桌面应用程序运行时没有崩溃。

An example of the proper conversion from Swift 3 to 4 below for your Node class: 以下是您的Node类从Swift 3正确转换为4的示例:

class Node: NSObject, TreeNode {
    @objc var name1: String
    @objc var name2: String
    @objc var name3: String?

    @objc var children: [Node] = []

    @objc init(name1: String, name2: String, name3: String) {
        self.name1 = name1
        self.name2 = name2
        self.name3 = name3
    }

    @objc func addChild(node: Node) {
       // add child function
    }

    @objc func findChild(node: Node) -> Node? {
       // find child function
    }
}

So for anyone running into this issue, when you convert to Swift 4, try using the 'Match Swift 3 Behavior' option. 因此,对于遇到此问题的任何人,当您转换为Swift 4时,请尝试使用“匹配Swift 3行为”选项。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM