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 th
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.
If you ask for opinion, this is mine: If one decides to mutate your
_myProtectedInt
he will probably succed anyway, because it's definitely possible with Objective-C runtime. Except this, your solution is quite OK.
For simple "properties" just use ivar instead. That's as good as properties for all practical purposes.
Moreover, the default is already protected.
Import the protected header in the implementation only. e.g.
ClassB.h
#import "ClassA.h"
@interface ClassB : ClassA
@end
ClassB.m
#import "ClassA_protected.h"
@implementation ClassB
@end
And in a framework the protected header should be marked project so it is not included in the public headers of the framework. Apple usually use the suffix _Internal.h for their protected methods.
For init or overriding a lazy loaded get property you would need direct access to the @proteced ivar, however for your use it would be better to redeclare the property as readwrite instead then you can take advantage of any features of the setter, atomicity for example.