ios - Swift NSTimer 将 userInfo 检索为 CGPoint

标签 ios swift nstimer userinfo

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,然后在 shoot() 函数中访问它。但是,现在我收到一条错误消息

1) 调用中的额外参数选择器

2) 无法转换表达式类型AnyObject?到CGPoint

现在我似乎无法将 userInfo 传递给其他函数然后检索它。

最佳答案

不幸的是 CGPoint 不是一个对象(至少在 Objective-C 世界中,Cocoa API 起源于此)。它必须包装在 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")
}

关于ios - Swift NSTimer 将 userInfo 检索为 CGPoint,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27133228/

相关文章:

ios - 如何检测 UIScrollView 是否空闲超过 500 毫秒?

xcode - 使用 Swift 的 TableViewController 和 CustomCell

ios - 暂停/恢复 NSTimer

ios - 我无法删除使用苹果登录的用户

ios - 如何在 Objective C 中重置计时器?

ios - 使用 Swift 的计时器只倒计时 20 秒,而不是二十分钟

ios - 如何在Xcode 4.2中“添加现有文件”?

ios - 无法在模拟器中运行应用程序

ios - 测试应用内购买,无需在 iTunes 中提交应用且未验证产品

swift - “Functions are a first-class type” swift ?