Swift 2,方法' setOn'使用Objective-C选择器' setOn:'与安装者的冲突与“#”;使用相同的Objective-C选择器

时间:2016-01-10 08:25:20

标签: ios objective-c swift2

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

我认为willSetdidSet不是解决方案,因为即使我添加了一些保护条件,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 ...
}

2 个答案:

答案 0 :(得分:5)

Compiler error: Method with Objective-C selector conflicts with previous declaration with the same Objective-C selector类似,您也可以隐藏属性 带有@nonobjc的Objective-C运行时:

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。

答案 1 :(得分:0)

而不是willSet您需要使用didSet

var on: Bool = false
{
    didSet
   {
        if self.on != oldValue
        {
            setOn(self.on, animated: false)
        }
    }
}