Workaround to accomplish protected properties in Objective-C

前端 未结 4 1960
你的背包
你的背包 2021-01-30 04:35

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

相关标签:
4条回答
  • 2021-01-30 04:51

    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.

    0 讨论(0)
  • 2021-01-30 04:56

    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.

    0 讨论(0)
  • 2021-01-30 05:02

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

    Moreover, the default is already protected.

    0 讨论(0)
  • 2021-01-30 05:02

    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.

    0 讨论(0)
提交回复
热议问题