{ by david linsin }

August 12, 2010

Private Properties in Objective-C

When a co-worker asked me if there's a way to declare a Objective-C property to be private, I could come up with an answer. Even after googling for a while, I couldn't find an example, easy enough to understand. Every time I have to search for something more than a couple of minutes and I can't find a definite source for an answer, I think it's worth a blog post.

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:

Unknown said...

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.

Doral real estate said...

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,

Zachary Shepherd said...

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.

Golden Gal said...

Nice post thankss for sharing


com_channels

  • mail(dlinsin@gmail.com)
  • jabber(dlinsin@gmail.com)
  • skype(dlinsin)

recent_postings

loading...