Search code examples
iosiphoneobjective-cios6ios7

Objective-C: How do I access parent private properties from subclasses?


//Super class .h file

@interface MySuperClass : NSObject

@end

//Super class .m file

@interface MySuperClass ()

@property (nonatomic, strong) UITextField *emailField; 

@end

@implementation MySuperClass

-(void)accessMyEmailField {

   NSLog(@"My super email: %@", self.emailField.text);

}

@end


// ********** my subclass *******

//Subclass .h file

@interface MySubClass : MySuperClass

@end

//SubClass .m file

@interface MySubClass ()

@end

@implementation MySubClass

-(void)myEmail {

   NSLog(@"My subclass email: %@", self.emailField.text);

}

-(void)setMyEmailFromSubclass{

   self.emailField.Text = @"[email protected]"

}

@end
  1. How do i access emailField in -(void)myEmail method.
  2. How do i set email in Subclass -(void)setMyEmailFromSubclass; , and access it in super class accessMyEmailField

Solution

  • You can put accessors to these properties in a second header file, and import that file on a 'need-to-know' basis.. eg

    mySuperClass+undocumentedProperties.h

    #import "mySuperClass.h"
    
    @interface mySuperClass(undocumentedProperties)
    
      @property (nonatomic, strong) UITextField *emailField;
    
     @end
    

    mySuperClass.m

    #import "mySuperClass+undocumentedProperties.h"
    
    @interface mySuperClass()
    ///stuff that truly will be private to this class only
    // self.emailField is no longer declared here..
    @end
    
    @implementation mySuperClass
    
    @synthesize emailField; //(not really needed anymore)
    
    /// etc, all your code unaltered
    @end
    

    mySubclass.h

    #import "mySuperClass.h"
    @interface mySubclass:mySuperClass
    
    ///some stuff
    @end
    

    mySubclass.m

    #import "mySubclass.h"
    #import "mySuperClass+undocumentedProperties.h"
    @implementation
    
    //off you go, this class is now 'aware' of this secret inherited property..
    
    @end
    

    obviously MySuperClass.m will have to import this .h file as well as its default one (or actually instead of, the default one is built in to this one), but your subclasses can import it too (directly into their .m file, so these properties remain private to the class. This is not a proper category because there is no corresponding mySuperClass+undocumentedProperties.m file (if you tried that you could not synthesize the backing iVars for these secret properties. Enjoy :)