Hiding properties from public access

后端 未结 6 732
攒了一身酷
攒了一身酷 2020-12-07 22:53

I\'m trying to declare properties that are for internal use only in a Private category as such:

@interface BarLayer (Private)

@property (readwr         


        
6条回答
  •  旧时难觅i
    2020-12-07 23:56

    I found an explanation of why synthesis of properties is prohibited in categories, but how you can use class extensions instead:

    The following information comes from http://www.friday.com/bbum/2009/09/11/class-extensions-explained/

    "The reason synthesis was prohibited in categories was because synthesis requires storage and there was no way of declaring storage in a category efficiently and it wasn’t deemed acceptable to allow a category to synthesize methods that would then diddle the class’s ivars directly. Too fragile and ugly.

    However, it was also obviously desirable to be able to declare a property that was publicly readonly, but whose implementation was readwrite for internal-to-the-class-or-framework purposes.

    One additional requirement is that the synthesis such properties must always be able to synthesize both the setter and getter naturally and precisely. Specifically, when declaring a property as atomic, there is no way the developer can correctly manually write only 1/2 of the getter setter pair; the locking infrastructure is not exposed and, thus, there is no way to guarantee atomicity in such a situation.

    Class extensions addressed this problem elegantly.

    Specifically, you can declare a property like:

    @interface MyClass : NSObject
    @property(readonly) NSView *targetView;
    @end
    

    And, then, in the implementation file:

    @interface MyClass()
    @property(readwrite) NSView *targetView;
    @end
    
    @implementation MyClass
    @synthesize targetView;
    @end
    

    End result? A property that is publicly readonly, but privately readwrite without opening properties up to all of the fun fragility associated with categories."

提交回复
热议问题