[英]Swift: Value of type has no member 'peformSelector'
I'm trying to implement protocol/delegate using performSelector but I'm getting this error: 我正在尝试使用performSelector来实现协议/代理,但出现此错误:
Value of type 'DoingSomething' has no member 'peformSelector'
Here is my implementation: 这是我的实现:
import UIKit
protocol DoingSomethingDelegate {
// delegate function
}
class DoingSomething {
func goDoSomething()
self.performSelector(onMainThread: #selector(self.processSomething()), with: nil, waitUntilDone: true)
}
func processSomething() {
print("I'm done")
}
}
But if I move the functions to the viewController I have no errors. 但是,如果我将函数移到viewController,则不会出错。 Any of you knows why of the error or how can I fix this error? 你们谁都知道错误的原因或如何解决该错误?
I'll really appreciate your help. 非常感谢您的帮助。
Per @dan comment I made the changes: 根据@dan评论,我进行了更改:
class DoingSomething:NSObject {
func goDoSomething() {
self.performSelector(onMainThread: #selector(self.processSomething), with: nil, waitUntilDone: true)
}
func processSomething() {
print("I'm done")
}
}
Now is working! 现在正在工作!
As @vandian suggests in his comment, you should think about using GCD instead. 正如@vandian在其评论中建议的那样,您应该考虑使用GCD。 The equivalent code would be: 等效代码为:
DispatchQueue.main.async {
self.processSomething()
}
There are a couple of advantages to using async(). 使用async()有两个优点。 You can provide the code in-line without having to write a separate function, which makes it easier to read and maintain; 您可以内联提供代码,而无需编写单独的函数,这使它的读取和维护更加容易。 The closure you execute has access to the enclosing scope, so you can use variables from your function inside that code, eg: 您执行的闭包可以访问封装范围,因此您可以在该代码内使用函数中的变量,例如:
func localScopeFunc {
var x: Int = 6
DispatchQueue.main.async {
//This block of code has access to the local variables from localScopeFunc
print("x = \(x)")
}
}
With performSelector() and it's variants you can only invoke functions with zero, one, or 2 arguments, and those arguments must be NSObjects
. 使用performSelector()及其变体,您只能调用带有零,一或两个参数的函数,并且这些参数必须是NSObjects
。
Forcing an object to be a subclass of NSObject
also has some minor down-sides to it. 强制对象成为NSObject
的子类也有一些小NSObject
。 That forces the compiler to use dynamic dispatching, which is slightly slower than the static dispatching that Swift uses. 这迫使编译器使用动态调度,这比Swift使用的静态调度要慢一些。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.