Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Workaround to accomplish protected properties in Objective-C

I've been trying to find a workaround to declare @protected properties in Objective-C so only subclasses in the hierarchy can access them (read only, not write). I read that there is no documented way of doing this so I thought of this workaround and I wanted to ask StackOverflow's opinion about it.

Every custom class at the top of the hierarchy contains three classes, one implementation and two interfaces. Let's name them:

ClassA.h ClassA_protected.h ClassA.m 

Then any subclass of this ClassA would be as usual:

ClassB.h ClassB.m 

First I created the interface ClassA.h where I declare a protected int variable so any subclass of ClassA can have access to it:

@interface ClassA : NSObject{     @protected     int _myProtectedInt; } @end 

Next step is the workaround I was talking about. However, once you read it you will see that it is quite straight forward. I declared a second interface called ClassA_protected.h which actually works as an extension of ClassA.h and allows us to tag the property as readonly:

#import "ClassA.h" @interface ClassA () @property (nonatomic , readonly) int myProtectedInt; @end 

Last step of preparing the protected hierarchy is to declare its implementation in ClassA.m where we only synthesize our property:

#import "ClassA_protected.h" @implementation ClassA @synthesize myProtectedInt = _ myProtectedInt; @end 

This way, every class that needs to be a subclass of ClassA.h, will import ClassA_protected.h instead. So a child like, for example ClassB.h, would be as follows:

#import "ClassA_protected.h" @interface ClassB : ClassA @end 

And an example of accessing this property from ClassB.m's implementation:

@implementation ClassB -(void) method {     //edit protected variable      _myProtectedInt= 1;      //normal access     self.muProtectedInt; } @end 
like image 484
Alex Salom Avatar asked Jun 15 '12 08:06

Alex Salom


People also ask

What is the use of property in Objective-C?

@property offers a way to define the information that a class is intended to encapsulate. If you declare an object/variable using @property, then that object/variable will be accessible to other classes importing its class.


2 Answers

Sure, that works fine. Apple uses the same approach for example in the UIGestureRecognizer class. Subclasses have to import the additional UIGestureRecognizerSubclass.h file and override the methods that are declared in that file.

like image 111
Ole Begemann Avatar answered Nov 08 '22 01:11

Ole Begemann


For simple "properties" just use ivar instead. That's as good as properties for all practical purposes.

Moreover, the default is already protected.

like image 23
Septiadi Agus Avatar answered Nov 07 '22 23:11

Septiadi Agus