Expose a private Objective-C method or property to subclasses

后端 未结 7 1366
栀梦
栀梦 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:17

    Simply create a .h file with your class extension. Import this into your .m files. Incidentally, this is a great way to test private members without breaking encapsulation (I'm not saying you should test private methods :) ).

    // MyClassProtectedMembers.h
    @interface MyClass()
    
    @property (nonatomic, strong) MyPrivateObject *privateObject;
    - (void) privateMethod;
    @end
    

    /////////////////

    #import "MyClassProtectedMembers.h"
    
    @implementation MyClass
    // implement privateMethod here and any setters or getters with computed values
    @end
    

    Here's a gist of the idea: https://gist.github.com/philosopherdog/6461536b99ef73a5c32a

提交回复
热议问题