EXC_BAD_ACESS iOS8 SpriteKit 崩溃

EXC_BAD_ACESS crash in SpriteKit on iOS8

我在尝试更改 SKSpriteNode 的位置时遇到了一个非常奇怪的崩溃。此崩溃发生在 iOS8 而不是 iOS9.

// if the powerup is full, spawn the icon on screen
if orangeBallsCollected == numberOfBallsRequiredToActivatePowerup {

    // add the powerup icon to the array of powerupiconsonscreen
    powerupIconsOnScreen.append(fewerColorsPowerupIcon)

    // set the lighting mask of the powerup icon so that we know what positon it is onscreen for alter
    fewerColorsPowerupIcon.lightingBitMask = UInt32(powerupIconsOnScreen.count - 1)

    // remove the ball from its current parent
    fewerColorsPowerupIcon.removeFromParent()

    print(fewerColorsPowerupIcon, fewerColorsPowerupIcon.parent, fewerColorsPowerupIcon.physicsBody, fewerColorsPowerupIcon.superclass)

    // place the ball of the screen so that we can bring it on later
    fewerColorsPowerupIcon.position = CGPointMake((width * -0.1) , (height * -0.1))

    // set the size of the icon
    fewerColorsPowerupIcon.xScale = scaleFactor
    fewerColorsPowerupIcon.yScale = scaleFactor

    // add it the scene
    self.addChild(fewerColorsPowerupIcon)

    // animate it moving down to the first avaliable position
    let animation = SKAction.moveTo(CGPoint(x: width * 0.1, y: height * 0.1), duration: 0.5)

    // run the animation!
    fewerColorsPowerupIcon.runAction(animation)

    // activate the poweurp
    activateFewerColors()

}

当我尝试设置位置 (fewerColorsPowerupIcon.position) 时发生崩溃,这是崩溃消息:

Thread 1: EXC_BAD_ACCESS(code=EXC_I386_GPFLT)

如果我在设置节点位置后放置 .removeFromParent() 段代码,仍然会发生此崩溃。

如果 fewerColorsPowerupIcon 声明如下:

 weak var fewerColorsPowerupIcon: Type!

然后一旦您调用 removeFromParent(),可能就不再有对它的强引用。如果是这样,则不能保证 fewerColorsPowerupIcon 将被设置为 nil 或者它会被检测到。下次使用它时,您可能会得到 EXC_BAD_ACCESS.

找到这样的东西的一种方法是使用僵尸工具。在它之下,没有对象在没有引用时真正被释放,但是如果你在所有强引用被释放后尝试使用它们,它们会抱怨。

另一种选择是更改 !到 ? (并更新使用 var 的代码)。这可能会很痛苦,但是关于如何做有更多保证?行为。

我觉得如果把精灵去掉就什么都做不了了

所以尝试这样做:

let spriteCopy =  fewerColorsPowerupIcon.copy()

// place the ball of the screen so that we can bring it on later
spriteCopy.position = CGPointMake((width * -0.1) , (height * -0.1))

// set the size of the icon
spriteCopy.xScale = scaleFactor
spriteCopy.yScale = scaleFactor

// add it the scene
self.addChild(spriteCopy)

或者你可以先在场景中添加,然后修改属性:

// remove the ball from its current parent
fewerColorsPowerupIcon.removeFromParent()

// add it the scene
self.addChild(fewerColorsPowerupIcon)

 // place the ball of the screen so that we can bring it on later
fewerColorsPowerupIcon.position = CGPointMake((width * -0.1) , (height * -0.1))

// set the size of the icon
fewerColorsPowerupIcon.xScale = scaleFactor
fewerColorsPowerupIcon.yScale = scaleFactor