Hiding properties from public access

后端 未结 6 734
攒了一身酷
攒了一身酷 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条回答
  •  醉话见心
    2020-12-07 23:35

    Because categories can only add methods to a class you can't get around this by trying to define property methods in the category.

    You can declare properties that are derived from already existing classes. For example. If your class has a firstName and a lastName property, you can declare a property called fullName in a category @implementation.

    @interface Bar (Private)
    @property (readonly) NSString *fullName; // Note readonly, you have nothing to write to.
    @end
    

    However, you can't just @synthesize this property, you would have to write your own accessor because the compiler has no idea where you want to get this value from.

    @implementation Bar (Private)
    - (NSString *)fullName {
        NSString *returnString = [NSString stringWithFormat:@"%@ %@", 
                                 self.firstName, self.lastName];
    }
    

    From a class design point of view, I'm not sure that the idea of a private property makes sense: I personally think of properties as something that are exposed publically by a class.

    you could use the @private keyword in the BarLayer class to at least add some protection to its state.

提交回复
热议问题