我正在使用NSNotificationCenter试图控制SpriteKit中的计时器。首次输入SKScene时,代码运行良好,但是当我尝试重新输入SKScene时,出现EXC_BAD_ACCESS错误。我认为这与removeObserver函数有关。我不确定何时删除观察者,我尝试在prepareForSegue函数中执行此操作,但未成功。我的viewController如下:
class JobStartedViewController: UIViewController {
var titleOfJob: String = ""
override func viewDidLoad() {
super.viewDidLoad()
let skView = self.view as! SKView
let scene:SKScene = GameScene.init(size: skView.bounds.size)
NSNotificationCenter.defaultCenter().postNotificationName("stopTimerNotification", object: nil)
NSNotificationCenter.defaultCenter().postNotificationName("startTimerNotification", object: nil)
/* Sprite Kit applies additional optimizations to improve rendering performance */
skView.ignoresSiblingOrder = true
/* Set the scale mode to scale to fit the window */
scene.scaleMode = .AspectFill
skView.presentScene(scene)
}
并将观察者添加到我的GameScene.swift中,如下所示:
class GameScene: SKScene {
override func didMoveToView(view: SKView) {
NSNotificationCenter.defaultCenter().addObserver(self, selector: "stopTimerInBackground:", name:"stopTimerNotification", object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "startTimerInBackground:", name:"startTimerNotification", object: nil)
以下是可能的事件流:
JobStartedViewController
,它将创建场景并将其添加到视图中,从而触发didMoveToView(_:)
并添加两个观察者。SKView
。不久之后的某个时刻,不再有对该场景的强大引用,并且将其释放。此时,通知中心中仍存在对其的不安全引用。JobStartedViewController
或以其他方式发布stopTimerNotification
通知。NSNotificationCenter
尝试在已取消分配的场景上执行选择器,导致应用崩溃。使用的通常做法NSNotificationCenter
是在dealloc
Objective-Cdeinit
方法或Swift方法中删除观察者:
class GameScene: SKScene {
// ...
deinit {
NSNotificationCenter.defaultCenter().removeObserver(self)
}
}
如果您打算多次在视图中添加和删除该场景,则还应考虑从中删除观察者willMoveFromView(_:)
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句