//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
-(void)myEmail method
.-(void)setMyEmailFromSubclass
; , and access it in super class accessMyEmailField
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 :)
Copy the private interface portion of the methods you want from your superclass - or in other words, in your Subclass.m file you would put:
@interface MySuperClass ()
@property (nonatomic, strong) UITextField *emailField;
@end
( place it above the existing @interface MySubClass ()
code )
Now your subclass knows that method exists in the superclass and can use it, but you are not exposing it to anyone else.
The whole point of private properties is exactly that and you should not want to access them. Because they are private they can change or be removed thus breaking the subclass that relies on them.
That being said they are not really private, just not "published". The can be called because Objective-C is a run-time dynamic language.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With