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

Я пытаюсь создать таймер, который периодически запускается и передает точку касания (CGPoint) как userInfo в NSTimer, а затем обращается к ней через функцию shoot(). Однако прямо сейчас я получаю сообщение об ошибке

1) дополнительный селектор аргументов при вызове

2) не может преобразовать выражение типа AnyObject? В CGPoint

Прямо сейчас я не могу передать userInfo другой функции, а затем получить ее.


person Wraithseeker    schedule 25.11.2014    source источник


Ответы (1)


К сожалению, CGPoint не является объектом (по крайней мере, в мире Objective-C, из которого происходят API-интерфейсы Cocoa). Он должен быть обернут в объект 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")
}
person Michał Ciuba    schedule 25.11.2014
comment
Если ответ решает вашу проблему, вы можете пометить его как принятый: stackoverflow.com/help/someone-answers. - person Michał Ciuba; 25.11.2014