ios - Swift 选择器 - 发送到实例的无法识别的选择器

标签 ios swift selector nstimer

我有一个函数:

func runRockRotation(rockSprite: SKSpriteNode){
    startRockRotationAnimation(rockSprite, isRock: true)
}

当我这样调用它时:

runRockRotation(rock)

它可以工作,但我似乎无法将它放入 NSTimer 选择器中。

var timer = NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: "runRockRotation:", userInfo: rock, repeats: false)

看了很多论坛,试过这个:

var timer = NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: "runRockRotation()", userInfo: rock, repeats: false)
var timer = NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: "runRockRotation(_)", userInfo: rock, repeats: false)
var timer = NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: "runRockRotation", userInfo: rock, repeats: false)

此外,尝试不使用 rock,使用 nil,但似乎没有任何效果。

每次我得到:

2015-04-10 15:49:03.830 Meh[1640:218030] -[__NSCFTimer runAction:completion:]: unrecognized selector sent to instance 0x174166840
2015-04-10 15:49:03.832 Meh[1640:218030] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFTimer runAction:completion:]: unrecognized selector sent to instance 0x174166840'

如何在带有参数的选择器中调用我的函数?我知道如何在 Objective C 中做到这一点,但似乎无法在 Swift 中做到这一点。我们将不胜感激。

最佳答案

查看 scheduledTimerWithTimeInterval 的文档

你会看到

The selector should have the following signature: timerFireMethod: (including a colon to indicate that the method takes an argument).

The timer passes itself as the argument, thus the method would adopt the following pattern: - (void)timerFireMethod:(NSTimer *)timer

您的函数与此模式不匹配,因此找不到合适的选择器。

使用类似 -

func runRockRotationForTimer(_ timer: NSTimer){
    self.runRockRotation(timer.userInfo as? SKSpriteNode)
    timer.invalidate();
}

并安排它使用

var timer = NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: "runRockRotationForTimer:", userInfo: rock, repeats: false)

关于ios - Swift 选择器 - 发送到实例的无法识别的选择器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29562064/

相关文章:

ios - SwiftUI:扩大/缩小列表单元格

jquery - css 类选择器不工作,不知道为什么

android - ImageView 选择器不起作用

ruby-on-rails - 预期 CSS "Home"返回一些 RSpec 问题

ios - 如何同时获取更新(currentTime :) function uses?(调用前)

IOS视差和PageControll

ios - SceneKit 不会在 Xcode 12 中填满屏幕

ios - 在 iOS 中访问和操作 Google 表格

ios - 将 Alamofire POST 的 JSON 响应转换为可以显示的变量

ios - 为什么iOS 10 Calendar.current.timeZone不返回我的本地时区?