如何在swift中对performSelector使用默认协议实现?
问题描述:
我通过创建该协议的扩展来创建了一个使用单个方法和默认实现的协议。我的应用程序崩溃,因为执行选择器不能识别默认实现。如何在swift中对performSelector使用默认协议实现?
该方法实际上可以直接调用,没有问题。对该方法使用respondsToSelector将返回false,对方法崩溃则使用performSelector。
在实际的类或类的扩展中实现协议使其工作,但这违背了默认实现的目的。
我也向苹果提交了一个错误报告。
public protocol TestProtocol
{
func testMethod()
}
extension TestProtocol
{
public func testMethod() {
print("testing the method...")
}
}
class ViewController: UIViewController, TestProtocol {
@IBOutlet weak var button: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.button.addTarget(self, action: "testMethod", forControlEvents: UIControlEvents.TouchUpInside)
print(self.respondsToSelector("testMethod"))
self.testMethod()
// self.performSelector("testMethod")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
答
解决方法是只定义一些其他方法,并调用默认方法。
这不是一个真正的错误,但是尝试在协议和扩展方法中添加@objc。这可能只是不起作用,协议扩展在Objc中没有意义。 – 2015-10-13 23:53:45
不可以,扩展名不能使用“@objc”。在协议方法中放置“@objc”使得默认的实现不会被实际使用。这非常迫使我在课堂上实施它。因此,无法使用选择器调用协议方法的默认实现,因为协议扩展不能与objective-c一起使用。 – rexcalibur
是的,这很有道理。通过让所有的类“分开”实现它们,没有理由协议扩展不能在Objective-C中工作,但我怀疑Swift团队是否会实现它。 – 2015-10-14 14:11:07