简体   繁体   中英

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

After Swift 4 migration, my NSTreeController project now crashes on start. I boiled it down to the casting of @objc to my dynamic array. 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. 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.

An example of the proper conversion from Swift 3 to 4 below for your Node class:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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