NSTimer不允许我将自己用作目标?

时间:2016-02-17 01:05:35

标签: ios xcode swift sprite-kit

每当我尝试使用NSTimer使用目标self时,会弹出错误

  

参数类型'NSObject-> () - > GameScene'不符合预期类型'AnyObject'。

为了安全起见,我还尝试添加AnyObject代替self

class GameScene: SKScene {

    var point = SKSpriteNode(imageNamed: "Point")
    override func didMoveToView(view: SKView) {

    }

    var timer = NSTimer.scheduledTimerWithTimeInterval(0.0001, target: self, selector: ("stroke"), userInfo: nil, repeats: true)

    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
        for touch in touches {
            let location = touch.locationInNode(self)
            func stroke(){
                point.position = CGPoint(x: location.x, y: location.y)
                self.addChild(point)
            }
        }
    }
}

1 个答案:

答案 0 :(得分:3)

我认为问题是你在声明变量时调用函数,而且很可能还没有创建self或object 这就是你收到错误的原因。

在构造函数或初始化期间调用的函数中移动函数调用,它应该没问题。

var timer : NSTimer!
...
...
func someFunc()
{
  timer = NSTimer.scheduledTimerWithTimeInterval(0.0001, target: self, selector: ("stroke"), userInfo: nil, repeats: true)
}