how to define a selector in swift3 for an override method(如何在swft3中为重写方法定义选择器)
问题描述
我想在CBPeripheralDelegate中定义一个选择器,它是func peripheral(peripheral: CBPeripheral, didUpdateValueForCharacteristic characteristic: CBCharacteristic, error: NSError?)
。
在swft3中,更名为peripheral(_: didUpdateValueFor:error)
,与func peripheral(peripheral: CBPeripheral, didUpdateValueForDescriptor descriptor: CBDescriptor, error: NSError?)
相同
因此,当我尝试这样定义选择器时,#selector(CBPeripheralDelegate.peripheral(_:didUpdateValueFor:error:))
将导致编译错误:ambiguous use
。
#selector(((CBPeripheralDelegate.peripheral(_:didUpdateValueFor:error:)) as (CBPeripheralDelegate) -> (CBPeripheral, CBCharacteristic, NSError) -> Void)
,
两者均未通过。
那么,在wift3中定义选择器的正确方式是什么?
推荐答案
恐怕这可能是当前#selector
表示法中的缺陷,您应该将错误报告发送到Apple或swift.org。(或者我可能只是错过了一些东西...)
若要解决此问题,请定义一个符合协议的类,并定义要为其创建选择器的方法。
class TheClass: NSObject, CBPeripheralDelegate {
func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?) {
//No need to actually implement the method
}
}
并在#selector()
中使用该类名:
#selector(TheClass.peripheral(_:didUpdateValueFor:error:))
您可能已经有一个实现该方法的类,然后您可以使用它的类名。
Objective-C选择器不保留类名信息,因此,该选择器可用于可能正在实现该方法的任何类。
如果要从符合协议并具有方法定义的类内部创建选择器,可以将其编写为:
#selector(peripheral(_:didUpdateValueFor:error:))
这篇关于如何在swft3中为重写方法定义选择器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!