Swift 2,我有一个继承自objc的UIView的类,它有'on'变量,以及相关方法'setOn:animated'和'setOn:',如下所示:
public class AView: UIView { var on: Bool = false public func setOn(on: Bool, animated: Bool) { self.on = on // do something more about animating } public func setOn(on: Bool) { setOn(on, animated: false) }
我收到一条错误消息: method 'setOn' with Objective-C selector 'setOn:' conflicts with setter for 'on' with the same Objective-C selector
我认为willSet
或didSet
不是解决方案,因为setOn:animated:
即使我添加了一些保护条件,也会被调用两次:
var on: Bool = false { willSet { if self.on != newValue { setOn(self.on, animated: false) } } } .... .... let a = AView() a.setOn(true, animated: true) // setOn:animated: is called twice
有没有更改变量名称和方法名称的解决方案?
解决方法:我的解决方案是添加额外的内部变量并使用computed属性公开它.我不喜欢添加额外的变量,肯定会有更好的解决方案.
private var isOn: Bool = false var on: Bool { set(newOn) { setOn(newOn, animated: false) } get { return isOn } } public func setOn(on: Bool, animated: Bool) { self.isOn = on // do something ... }
Martin R.. 5
与编译器错误类似:使用Objective-C选择器的方法与先前使用相同Objective-C选择器的声明冲突,您还可以使用以下方法隐藏Objective-C运行时中的属性@nonobjc
:
public class AView: UIView { @nonobjc var on: Bool = false public func setOn(on: Bool, animated: Bool) { self.on = on // do something more about animating } public func setOn(on: Bool) { setOn(on, animated: false) } }
这可以防止自动生成冲突的Objective-C setter.
与编译器错误类似:使用Objective-C选择器的方法与先前使用相同Objective-C选择器的声明冲突,您还可以使用以下方法隐藏Objective-C运行时中的属性@nonobjc
:
public class AView: UIView { @nonobjc var on: Bool = false public func setOn(on: Bool, animated: Bool) { self.on = on // do something more about animating } public func setOn(on: Bool) { setOn(on, animated: false) } }
这可以防止自动生成冲突的Objective-C setter.