Swift NSTimer retrieving userInfo as CGPoint

862 views Asked by At
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

There are 1 answers

0
Michał Ciuba On BEST ANSWER

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")
}