Swift NSTimer将用户信息检索为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") }
我正在尝试创build一个计时器,该计时器将周期性地运行,将触摸点(CGPoint)作为userInfo传递给NSTimer,然后在shoot()函数中访问它。 但是,现在我得到一个错误,说
1)调用中的额外参数select器
2)不能转换expression式typesAnyObject? 到CGPoint
现在我似乎无法将userInfo传递给另一个函数,然后检索它。
不幸的是, CGPoint
不是一个对象(至less在Cocoa API起源的Objective-C世界中)。 它必须被包装在一个NSValue
对象中以放入一个集合中。
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") }