ios - 如何在 swift 中使用 performSelector 实现回调/选择器?
<p><p>我正在尝试用 swift 语言创建与以下方法签名 (Objective-C) 等效的方法。我无法得到关于如何为此获得正确等价物的答案。非常感谢任何帮助。</p>
<pre><code>- (void)myMethod:(MyObject*)firstParam
setCallbackObject:(id)obj
withMySelector:(SEL)selector {
}
</code></pre></p>
<br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
<p><p>第一:</p>
<p> <a href="https://developer.apple.com/library/prerelease/mac/documentation/Swift/Conceptual/BuildingCocoaApps/InteractingWithObjective-CAPIs.html" rel="noreferrer noopener nofollow">NOTE</a> </p>
<blockquote>
<p>The performSelector: method and related selector-invoking methods are not imported in Swift because they are inherently unsafe.</p>
</blockquote>
<p><em>如果您仍想以这种方式实现它,请阅读下文。</em></p>
<hr/>
<p>你可以使用 <code>NSTimer</code>:</p>
<pre><code>var myTimer: NSTimer = NSTimer.scheduledTimerWithTimeInterval(0.0, target: self, selector: "selectorMethod", userInfo: nil, repeats: false)
</code></pre>
<p><em>String 可以用在需要 <code>Selector</code> 的地方。它将自动转换(自动装箱)。</em></p>
<p><em>延迟当然可以更高:0.1 等于十分之一秒。</em></p>
<p>调用类似的方法:</p>
<pre><code>func selectorMethod() {
...
}
</code></pre>
<hr/>
<p>我们需要在类上使用选择器之前进行检查。但是 <code>respondsToSelector:</code> 在 <code>NSObject</code> 协议(protocol)中,因此您必须至少从该协议(protocol)(或从它的子类)派生。</p>
<p>为了清楚起见,这里是例子。</p>
<h3>代码:</h3>
<pre><code>class Test {
func myMethod(firstParam: String, setCallbackObject obj: AnyObject, withMySelector selector: Selector) {
if obj.respondsToSelector(selector) {
var myTimer: NSTimer = NSTimer.scheduledTimerWithTimeInterval(0.0, target: obj, selector: selector, userInfo: nil, repeats: false)
myTimer.fire()
} else {
println("Warning: does not respond to given selector")
}
}
}
class Test2: NSObject {
func selectorMethod() {
print("worked")
}
}
var test: Test = Test()
var callBackObj: Test2 = Test2()
test.myMethod("thisfirstis", setCallbackObject: callBackObj, withMySelector: Selector("selectorMethod"))
</code></pre>
<h3>输出:</h3>
<blockquote>
<p>workedProgram ended with exit code: 0</p>
</blockquote></p>
<p style="font-size: 20px;">关于ios - 如何在 swift 中使用 performSelector 实现回调/选择器?,我们在Stack Overflow上找到一个类似的问题:
<a href="https://stackoverflow.com/questions/24468577/" rel="noreferrer noopener nofollow" style="color: red;">
https://stackoverflow.com/questions/24468577/
</a>
</p>
页:
[1]