Workaround to accomplish protected properties in Objective-C

前端 未结 4 1966
你的背包
你的背包 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条回答
  •  梦毁少年i
    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.

提交回复
热议问题