How to properly subclass a delegate property in Objective-C?

后端 未结 2 1929
无人共我
无人共我 2021-02-04 13:52

In subclassing a class, I want to also subclass a delegate of the parent class given that the subclass now has additional functionality. What\'s the best way to go about doing

2条回答
  •  傲寒
    傲寒 (楼主)
    2021-02-04 13:59

    Given this example that produces the warning:

    // Class A
    @protocol ClassADelegete;
    
    @interface ClassA : NSObject
    @property (nonatomic, weak) id delegate;
    @end
    
    @protocol ClassADelegete 
    - (void)classADidSomethingInteresting:(ClassA *)classA;
    @end
    
    // Class B
    @protocol ClassBDelegete;
    
    @interface ClassB : ClassA
    @property (nonatomic, weak) id delegate; // Warning here
    @end
    
    @protocol ClassBDelegete 
    - (void)classBDidSomethingElse:(ClassB *)classB;
    @end
    

    Two solutions that remove the warning are.

    1) In the subclass, place the protocol definition before the class definition. This is what UITableViewDelegate in UITableView.h does:

    // Class B
    @class ClassB;
    
    @protocol ClassBDelegete 
    - (void)classBDidSomethingElse:(ClassB *)classB;
    @end
    
    @interface ClassB : ClassA
    @property (nonatomic, weak) id delegate;
    @end
    

    2) In the subclass, add the original protocol alongside the new one:

    // Class B
    @protocol ClassBDelegete;
    
    @interface ClassB : ClassA
    @property (nonatomic, weak) id delegate;
    @end
    
    @protocol ClassBDelegete 
    - (void)classBDidSomethingElse:(ClassB *)classB;
    @end
    

    I assume (1) works as Apple do it this way, Option (2) removes the warning but I haven't compiled and run anything setup this way.

提交回复
热议问题