Hide instance variable from header file in Objective C

后端 未结 10 993
梦如初夏
梦如初夏 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条回答
  •  一整个雨季
    2020-12-30 14:46

    You can use a class extension. A class extension is similar as category but without any name. On the Apple documentation they just define private methods but in fact you can also declare your internal variables.

    MyClass.h

    @class PublicClass;
    
    // Public interface 
    @interface MyClass : NSObject
    
    @property (nonatomic, retain) PublicClass *publicVar;
    @property (nonatomic, retain) PublicClass *publicVarDiffInternal;
    
    - (void)publicMethod;
    
    @end
    

    MyClass.m

    #import "PublicClass.h"
    #import "InternalClass.h"
    
    // Private interface
    @interface MyClass ( /* class extension */ ) 
    {
    @private
        // Internal variable only used internally
        NSInteger defaultSize;
    
        // Internal variable only used internally as private property
        InternalClass *internalVar;  
    
    @private 
        // Internal variable exposed as public property 
        PublicClass *publicVar;
    
        // Internal variable exposed as public property with an other name
        PublicClass *myFooVar;
    }
    
    @property (nonatomic, retain) InternalClass *internalVar;
    
    - (void)privateMethod;
    
    @end
    
    // Full implementation of MyClass
    @implementation MyClass
    
    @synthesize internalVar;
    @synthesize publicVar;
    @synthesize publicVarDiffInternal = myFooVar
    
    - (void)privateMethod 
    {
    }
    
    - (void)publicMethod 
    {
    }
    
    - (id)init
    {
       if ((self = [super init]))
         {
           defaultSize = 512;
           self.internalVar = nil;
           self.publicVar = nil;
           self.publicVarDiffInternal = nil; // initialize myFooVar
         }
    
       return self;
    }
    @end
    

    You can give MyClass.h to anyone with just your public API and public properties. On MyClass.m you declare your member variable private and public, and your private methods, on your class extension.

    Like this it's easy to expose public interfaces and hide detail implementation. I used on my project without any troubles.

提交回复
热议问题