Extending a delegate from a base class

隐身守侯 提交于 2019-12-19 21:18:09

问题


I have an objc base class:

@protocol BaseClassDelegate;

@interface BaseClass : NSObject

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

@end

@protocol BaseClassDelegate <NSObject>

-(void)baseDelegateMethod;

@end

I am creating a swift sub-class in which I want to extend my delegate...

protocol SubClassDelegate : BaseClassDelegate {

    func additionalSubClassDelegateMethod();
}

class SubClass: BaseClass {

    @IBAction func onDoSomething(sender: AnyObject) {

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

Now, when I create my sub-class, I can say it conforms to the SubClassDelegate and set the delegate. The problem is (of course), is that 'delegate' doesn't exist in this sub-class. Is there a way to tell the compiler to 'extend' my delegate into my sub-class? (or am I being insane here and missed something obvious)


回答1:


I'd either create a wrapper delegate to make it the correct type in SubClass.

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

Or simply cast the delegate to the expected type:

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



回答2:


Here's a more comprehensive example of how to do this. Thanks to redent84 for pointing me in the right direction.

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()
        }
    }
}

And then in your implementation:

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

    func subclassDelegateMethod() {
        // yay! 
    }
}


来源:https://stackoverflow.com/questions/30911655/extending-a-delegate-from-a-base-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!