我试图在Swift中创建一个NSTimer,但我遇到了一些麻烦。

NSTimer(timeInterval: 1, target: self, selector: test(), userInfo: nil, repeats: true)

Test()是同一个类中的一个函数。


我在编辑器中得到一个错误:

无法找到一个超载的'init'接受提供的 参数

当我把selector: test()改为selector: nil时,错误就消失了。

我试过了:

选择器:测试() 选择器:测试 选择器:选择器(测试())

但是什么都没用,我在参考文献中找不到解决方案。


当前回答

objective - c选择器

Selector标识一个方法。

//Compile time
SEL selector = @selector(foo);

//Runtime
SEL selector = NSSelectorFromString(@"foo");

例如

[object sayHello:@"Hello World"];
//sayHello: is a selector

selector是一个来自Objective-C世界的词,你可以从Swift中使用它,有可能从Swift中调用Objective-C,它允许你在运行时执行一些代码

在Swift 2.2之前,语法是:

Selector("foo:")

因为函数名是作为字符串参数("foo")传入Selector的,所以在编译时不可能检查名称。结果你会得到一个运行时错误:

unrecognized selector sent to instance

在Swift 2.2+之后,语法是:

#selector(foo(_:))

Xcode的自动完成功能帮助你调用正确的方法

其他回答

选择器是Objective-C中方法名的内部表示。在Objective-C中,“@selector(methodName)”会将一个源代码方法转换为SEL的数据类型。因为你不能在Swift中使用@selector语法(里克斯特就在这里),你必须手动指定方法名直接作为String对象,或者通过传递String对象给Selector类型。这里有一个例子:

var rightBarButton = UIBarButtonItem(
    title: "Logout", 
    style: UIBarButtonItemStyle.Plain, 
    target: self, 
    action:"logout"
)

or

var rightBarButton = UIBarButtonItem(
    title: "Logout", 
    style: UIBarButtonItemStyle.Plain, 
    target: self, 
    action:Selector("logout")
)

选择器在Swift 4:

button.addTarget(self, action: #selector(buttonTapped(sender:)), for: UIControlEvents.touchUpInside)

下面是一个关于如何在Swift上使用Selector类的快速示例:

override func viewDidLoad() {
    super.viewDidLoad()

    var rightButton = UIBarButtonItem(title: "Title", style: UIBarButtonItemStyle.Plain, target: self, action: Selector("method"))
    self.navigationItem.rightBarButtonItem = rightButton
}

func method() {
    // Something cool here   
}

请注意,如果作为字符串传递的方法不起作用,它将在运行时失败,而不是在编译时失败,并使应用程序崩溃

Swift 3

//创建定时器的示例代码

Timer.scheduledTimer(timeInterval: 1, target: self, selector: (#selector(updateTimer)), userInfo: nil, repeats: true)

WHERE
timeInterval:- Interval in which timer should fire like 1s, 10s, 100s etc. [Its value is in secs]
target:- function which pointed to class. So here I am pointing to current class.
selector:- function that will execute when timer fires.

func updateTimer(){
    //Implemetation 
} 

repeats:- true/false specifies that timer should call again n again.

只是为了以防别人有同样的问题,我与NSTimer没有其他答案固定的问题,是真正重要的提到,如果你正在使用一个类,不继承从NSObject直接或深层的层次结构(例如。手动创建的swift文件),其他答案都不会工作,即使指定如下:

let timer = NSTimer(timeInterval: 1, target: self, selector: "test", 
                    userInfo: nil, repeats: false)
func test () {}

除了从NSObject继承类之外,没有改变任何其他东西,我停止了“Unrecognized selector”错误,并让我的逻辑按预期工作。