Swift NSTimer retrieving userInfo as CGPoint

☆樱花仙子☆ 提交于 2020-01-06 04:01:11

问题


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:


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


来源:https://stackoverflow.com/questions/27133228/swift-nstimer-retrieving-userinfo-as-cgpoint

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!