Swift NSTimer 将 userInfo 检索为 CGPoint [英] Swift NSTimer retrieving userInfo as CGPoint
问题描述
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")
}
我正在尝试创建一个定期运行的计时器,该计时器将触摸点 (CGPoint) 作为 userInfo 传递给 NSTimer,然后通过 shot() 函数访问它.但是,现在我收到一个错误,内容为
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) 调用中的额外参数选择器
1) extra argument selector in call
2) 不能转换表达式类型 AnyObject?到 CGPoint
2) cannot convert expression type AnyObject? To CGPoint
现在我似乎无法将 userInfo 传递给另一个函数然后检索它.
Right now I can't seem to pass the userInfo over to the other function and then retrieving it.
推荐答案
不幸的是 CGPoint
不是一个对象(至少在 Cocoa API 起源于 Objective-C 的世界中).它必须包装在 NSValue
对象中才能放入集合中.
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")
}
这篇关于Swift NSTimer 将 userInfo 检索为 CGPoint的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!