【问题标题】:How to prevent crashing when tapping off a node点击节点时如何防止崩溃
【发布时间】:2019-05-15 13:37:11
【问题描述】:

我正在编写的代码存在一个问题,即每当我点击节点以外的某个地方(例如背景)时,应用程序最终都会崩溃。

我尝试过创建一个 if let 语句,但它说我不能将 SKnode 向下转换为更可选的类型 SKSpriteNode。 我也试过if node.contains(position of touch)

 override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    let touch = touches.first
    if let touchLocation = touch?.location(in: self) {
    let selectedNode = nodes(at: touchLocation)[0] as! SKSpriteNode

        activeObject = selectedNode
        storedData = Array(activeObject.name!)
        let platformStoredInt = storedData[2]
        storedPlatform = Int(platformStoredInt.unicodeScalars.first!.value - Unicode.Scalar("0")!.value)

        }
    }

点击除被视为对象的 SKSpriteNode 之外的任何内容都会导致 SIGABRT。

【问题讨论】:

    标签: swift xcode sprite-kit


    【解决方案1】:

    应用程序崩溃是因为您在此行中强制解包一个值:

    let selectedNode = nodes(at: touchLocation)[0] as! SKSpriteNode

    因此,请改用:

    if let selectedNode = nodes(at: touchLocation)[0] as? SKSpriteNode {
    
      activeObject = selectedNode
      storedData = Array(activeObject.name!)
      let platformStoredInt = storedData[2]
       storedPlatform = Int(platformStoredInt.unicodeScalars.first!.value - Unicode.Scalar("0")!.value)
    
    }
    

    始终尽量避免强制展开(as!)。请改用Optional Chaining

    可选链是查询和调用当前可能为 nil 的可选的属性、方法和下标的过程。

    【讨论】:

    • 这有助于点击其他节点,但点击后台仍然会崩溃。
    • 我有一个 SIGABRT。
    • libc++abi.dylib:以 NSException 类型的未捕获异常终止
    猜你喜欢
    • 1970-01-01
    • 2010-11-05
    • 2013-03-20
    • 2017-01-26
    • 1970-01-01
    • 2022-01-14
    • 1970-01-01
    • 2012-12-27
    • 2020-02-18
    相关资源
    最近更新 更多