Declaring a private property is easy, once you understood the concept of Categories and Extensions:
A category can add methods to any class, including the root class. Methods added to NSObject become available to all classes that are linked to your code.
Maybe you've used this before to enhance the functionality of a framework class. I've used it e.g. to add a shuffle method to NSArray. Extensions take the concept of a category one step further:
Class extensions are like “anonymous” categories, except that the methods they declare must be implemented in the main @implementation block for the corresponding class.
With an extension, you can easily implement private property declarations:
The @private declaration takes care of protecting the instance variable age, only the Person implementation is allowed to access it. The class extension in Person.m declares the property and it's being synthesized just the way you would with a public property.
Due to the anonymous nature of the class extension, nobody including the Person.h file can see the synthesized getters and setters, hence a private property.
4 comments:
This is great David. I am a big fan of hiding implementation as much as possible.
In fact you don't need to declare age in the .h file at all as the compiler will generate it automatically from the @property declaration. I was using this to simplify my .h files.
With private properties I can further simplify things by keeping my internal properties hidden while still enjoying the retain/release benefits I get from using a properties.
This is a superb information and you have described everything very clearly and really i got a lot from this article, Thanks for spreading this information here,
A good way to hide implementations completely. I wouldn't want someone else to know my exact details either. I will follow this guide closely so I can use it whenever I need it.
Nice post thankss for sharing
Post a Comment