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

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

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


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

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

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

我试过了:

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

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


当前回答

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中传递一个参数给函数,那么这里是你的解决方案:

var somethingToPass = "It worked"

let timer = NSTimer.scheduledTimerWithTimeInterval(0.01, target: self, selector: "tester:", userInfo: somethingToPass, repeats: false)

func tester(timer: NSTimer)
{
    let theStringToPrint = timer.userInfo as String
    println(theStringToPrint)
}

在选择器文本(tester:)中包含冒号,参数则放在userInfo中。

你的函数应该以NSTimer作为参数。然后提取userInfo以获得传递的参数。

Swift本身并不使用选择器——Objective-C中使用选择器的几种设计模式在Swift中工作方式不同。(例如,在协议类型或is/as测试上使用可选链接,而不是respondsToSelector:,并在任何可以使用闭包的地方使用闭包,而不是performSelector:,以获得更好的类型/内存安全性。)

但是仍然有许多重要的基于objc的api使用选择器,包括计时器和目标/动作模式。Swift提供了Selector类型来处理这些。(Swift自动使用这个来代替ObjC的SEL类型。)

在Swift 2.2 (Xcode 7.3)及以后版本中(包括Swift 3 / Xcode 8和Swift 4 / Xcode 9):

你可以使用# Selector表达式从Swift函数类型中构造一个Selector。

let timer = Timer(timeInterval: 1, target: object,
                  selector: #selector(MyClass.test),
                  userInfo: nil, repeats: false)
button.addTarget(object, action: #selector(MyClass.buttonTapped),
                 for: .touchUpInside)
view.perform(#selector(UIView.insertSubview(_:aboveSubview:)),
             with: button, with: otherButton)

这种方法的好处是什么?函数引用是由Swift编译器检查的,所以你只能对实际存在的类/方法对使用#selector表达式,并且有资格作为选择器使用(参见下面的“选择器可用性”)。你也可以按照Swift 2.2+中函数类型命名的规则,根据你的需要来指定你的函数引用。

(这实际上是对ObjC的@selector()指令的改进,因为编译器的- wundeclated -selector检查只验证命名的选择器是否存在。你传递给#selector的Swift函数引用检查是否存在,类中的成员和类型签名。)

对于传递给#selector表达式的函数引用,有几个额外的注意事项:

Multiple functions with the same base name can be differentiated by their parameter labels using the aforementioned syntax for function references (e.g. insertSubview(_:at:) vs insertSubview(_:aboveSubview:)). But if a function has no parameters, the only way to disambiguate it is to use an as cast with the function's type signature (e.g. foo as () -> () vs foo(_:)). There's a special syntax for property getter/setter pairs in Swift 3.0+. For example, given a var foo: Int, you can use #selector(getter: MyClass.foo) or #selector(setter: MyClass.foo).

将军指出:

#selector不起作用的情况和命名:有时你没有函数引用来创建选择器(例如,在ObjC运行时动态注册的方法)。在这种情况下,你可以从一个字符串构造一个Selector:例如Selector("dynamicMethod:") -尽管你失去了编译器的有效性检查。当你这样做的时候,你需要遵循ObjC命名规则,包括每个参数的冒号(:)。

选择器可用性:选择器引用的方法必须公开给ObjC运行时。在Swift 4中,每个暴露给ObjC的方法的声明都必须以@objc属性开头。(在以前的版本中,在某些情况下你可以免费获得该属性,但现在你必须显式地声明它。)

记住,私有符号也不会向运行时公开——您的方法至少需要具有内部可见性。

键路径:它们与选择器相关,但并不完全相同。在Swift 3中也有一个特殊的语法:例如chris.valueForKeyPath(#keyPath(Person.friends.firstName))。具体请参见SE-0062。在Swift 4中甚至有更多的KeyPath内容,所以请确保您使用了正确的基于KeyPath的API,而不是选择器。

你可以在Using Swift with Cocoa和Objective-C中阅读更多关于与Objective-C api交互的选择器。

注意:在Swift 2.2之前,选择器符合StringLiteralConvertible,所以你可能会发现旧代码中裸字符串被传递给接受选择器的api。你需要在Xcode中运行“Convert to Current Swift Syntax”,使用#selector来获取这些语法。

选择器是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")
)

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的自动完成功能帮助你调用正确的方法

同样,如果你的(Swift)类不是来自Objective-C类,那么你必须在目标方法名称字符串的末尾有一个冒号,你必须使用@objc属性与你的目标方法,例如。

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

@objc func method() {
    // Something cool here   
} 

否则你会在运行时得到一个“unrecognized Selector”错误。