Workaround to accomplish protected properties in Objective-C

限于喜欢 提交于 2019-12-02 16:21:53

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.

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

Moreover, the default is already protected.

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.

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!