Swift NSTimer retrieving userInfo as CGPoint

2019-07-31 17:43发布

override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
    let touch = touches.anyObject() as UITouch
    let touchLocation = touch.locationInNode(self)

    timer = NSTimer.scheduledTimerWithTimeInterval(0.5, target: self, selector: "shoot", userInfo: touchLocation, repeats: true) // error 1
}

func shoot() {
    var touchLocation: CGPoint = timer.userInfo // error 2
    println("running")
}

I am trying to create a timer that runs periodicly that passes the touched point (CGPoint) as userInfo to the NSTimer and then accessing it over at the shoot() function. However, right now I am getting an error that says

1) extra argument selector in call

2) cannot convert expression type AnyObject? To CGPoint

Right now I can't seem to pass the userInfo over to the other function and then retrieving it.

1条回答
爷、活的狠高调
2楼-- · 2019-07-31 17:59

Unfortunately CGPoint is not an object (at least in Objective-C world, from which Cocoa APIs originate). It has to be wrapped in a NSValue object to be put in a collection.

override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
    let touch = touches.anyObject() as UITouch
    let touchLocation = touch.locationInNode(self)
    let wrappedLocation = NSValue(CGPoint: touchLocation)

    timer = NSTimer.scheduledTimerWithTimeInterval(0.5, target: self, selector: "shoot:", userInfo: ["touchLocation" : wrappedLocation], repeats: true)
}

func shoot(timer: NSTimer) {
    let userInfo = timer.userInfo as Dictionary<String, AnyObject>
    var touchLocation: CGPoint = (userInfo["touchLocation"] as NSValue).CGPointValue()
    println("running")
}
查看更多
登录 后发表回答