Extending a delegate from a base class

后端 未结 2 817
日久生厌
日久生厌 2021-01-18 09:51

I have an objc base class:

@protocol BaseClassDelegate;

@interface BaseClass : NSObject

@property (nonatomic, weak) id  delegate;         


        
相关标签:
2条回答
  • 2021-01-18 10:14

    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();
    
    0 讨论(0)
  • 2021-01-18 10:28

    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! 
        }
    }
    
    0 讨论(0)
提交回复
热议问题