Swift 2,使用Objective-C选择器'setOn:'的方法'setOn'与使用相同Objective-C选择器的'on'设置方法发生冲突 [英] Swift 2, method 'setOn' with Objective-C selector 'setOn:' conflicts with setter for 'on' with the same Objective-C selector
问题描述
迅速2,我有一个从objc的UIView继承的类,它具有"on"变量,以及相关的方法"setOn:animated"和"setOn:",如下所示:
Swift 2, I have a class inherits from objc's UIView and it has 'on' variable, and related methods 'setOn:animated' and 'setOn:' like below:
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
And I got an error message: method 'setOn' with Objective-C selector 'setOn:' conflicts with setter for 'on' with the same Objective-C selector
我认为willSet
或didSet
不是解决方案,因为即使添加了一些保护条件,setOn:animated:
也被调用了两次:
I think willSet
or didSet
is not a solution because setOn:animated:
is called twice even if I add some guard conditions:
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
有没有不更改变量名和方法名的解决方案吗?
Is there a solution without changing a variable name and methods name?
解决方法:我的解决方案是添加额外的内部变量,并使用计算属性将其公开.我不喜欢添加额外的变量,肯定会有更好的解决方案.
Workaround: My solution is add extra internal variable and expose it with computed property. I don't like adding extra variable and definitely there will be a better solution.
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 ...
}
推荐答案
Similarly as in Compiler error: Method with Objective-C selector conflicts with previous declaration with the same Objective-C selector, you can also hide properties from
the Objective-C runtime with @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设置器.
which prevents a conflicting Objective-C setter from being auto-generated.
这篇关于Swift 2,使用Objective-C选择器'setOn:'的方法'setOn'与使用相同Objective-C选择器的'on'设置方法发生冲突的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!