从基类扩展委托

时间:2015-06-18 09:33:19

标签: ios objective-c swift delegates extend

我有一个objc基类:

@protocol BaseClassDelegate;

@interface BaseClass : NSObject

@property (nonatomic, weak) id <BaseClassDelegate> delegate;

@end

@protocol BaseClassDelegate <NSObject>

-(void)baseDelegateMethod;

@end

我正在创建一个swift子类,我想在其中扩展我的委托......

protocol SubClassDelegate : BaseClassDelegate {

    func additionalSubClassDelegateMethod();
}

class SubClass: BaseClass {

    @IBAction func onDoSomething(sender: AnyObject) {

        delegate?.additionalSubClassDelegateMethod();  <--- No such method in 'delegate'
    }
}

现在,当我创建我的子类时,我可以说它符合SubClassDelegate并设置委托。问题是(当然),是代表&#39;在这个子类中不存在。有没有办法告诉编译器扩展&#39;我的代表进入我的子课程? (或者我在这里疯了,错过了一些明显的东西)

2 个答案:

答案 0 :(得分:8)

我要创建一个包装器委托,使其在SubClass中成为正确的类型。

class SubClass: BaseClass {
    var myDelegate: SubClassDelegate? {
        get { return delegate as? SubClassDelegate }
        set { delegate = newValue }
    }
    @IBAction func onDoSomething(sender: AnyObject) {
        myDelegate?.additionalSubClassDelegateMethod();
    }
}

或者只是将委托转换为预期的类型:

(delegate as? SubClassDelegate)?.additionalSubClassDelegateMethod();

答案 1 :(得分:6)

以下是如何执行此操作的更全面的示例。感谢redent84让我指向正确的方向。

protocol SubclassDelegate: ClassDelegate {
    func subclassDelegateMethod()
}

class Subclass: Class {
    // here we assume that super.delegate property exists
    @IBAction func buttonPressedOrSomeOtherTrigger() {
        if let delegate: SubclassDelegate = self.delegate as? SubclassDelegate {
            delegate.subclassDelegateMethod()
        }
    }
}

然后在您的实施中:

extension SomeOtherClass: SubclassDelegate {
    let someObject = Subclass()
    someObject.delegate = self

    func subclassDelegateMethod() {
        // yay! 
    }
}