Expose a private Objective-C method or property to subclasses

后端 未结 7 1334
栀梦
栀梦 2020-12-05 06:43

According to some official talk, a class in Objective-C should only expose public methods and properties in its header:

@interface MyClass : NSObject

@prope         


        
7条回答
  •  温柔的废话
    2020-12-05 07:19

    I see good answers for making properties visible, but I don't see exposing the methods addressed very clearly in any of these answers. Here is how I have successfully exposed private methods to the subclass using a Category:

    SomeSuperClass.m:

    @implementation SomeSuperClass
    
    -(void)somePrivateMethod:(NSString*)someArgument {
        ...
    }
    

    SomeChildClass.h

    @interface SomeChildClass : SomeSuperClass
    

    SomeChildClass.m

    @interface SomeSuperClass (exposePrivateMethod)
    -(void)somePrivateMethod:(NSString*)someArgument;
    @end
    
    @implementation SomeChildClass
    
    -(void)doSomething {
        [super somePrivateMethod:@"argument"];
    }
    
    @end
    

提交回复
热议问题