Hide instance variable from header file in Objective C

后端 未结 10 1066
梦如初夏
梦如初夏 2020-12-30 14:35

I came across a library written in Objective C (I only have the header file and the .a binary). In the header file, it is like this:

@interface MyClass : MyS         


        
10条回答
  •  猫巷女王i
    2020-12-30 14:59

    How about a macro trick?

    Have tested code below

    • have tested with dylibs - worked fine
    • have tested subclassing - Warning! will break, I agree this makes the trick not that useful, but still I think it tells some about how ObjC works...

    MyClass.h

    @interface MyClass : NSObject {
    #ifdef MYCLASS_CONTENT
        MYCLASS_CONTENT // Nothing revealed here
    #endif
    }
    @property (nonatomic, retain) NSString *name;
    @property (nonatomic, assign) int extra;
    - (id)initWithString:(NSString*)str;
    @end
    

    MyClass.m

    // Define the required Class content here before the #import "MyClass.h"
    #define MYCLASS_CONTENT \
      NSString *_name; \
      int _extra; \
      int _hiddenThing; 
    
    #import "MyClass.h"
    
    @implementation MyClass
    @synthesize name=_name;
    @synthesize extra=_extra;
    
    - (id)initWithString:(NSString*)str
    {
        self = [super init];
        if (self) {
            self.name = str;
            self.extra = 17;
            _hiddenThing = 19;
        }
        return self;
    }
    
    - (void)dealloc
    {
        [_name release];
        [super dealloc];
    }
    
    @end
    

提交回复
热议问题