inessential by Brent Simmons

Private properties and class extensions

I saw an Objective-C question on Twitter the other day — I forget who asked it (sorry about that) — but I figured I’d post an answer anway.

The question was something like this: “Do you use properties even for private instance variables?”

Answer: yes.

(I like properties. I like the way they simplify my code. I even like dot notation. If you don’t like properties, then ignore this.)

Here’s the thing: you can create private properties — you don’t have to declare all of them in the .h file. You can use a class extension (kind of like a category, but un-named) to declare properties.

It’s simple: in your .m file, add something like this:

@interface MyCoolObject ()
@property (nonatomic, retain) NSDictionary *myPrivateDictionary;
@end

Note the MyCoolObject () part — unlike a category, there’s no name for the interface. It’s an extension rather than a category.

(For more info, see the Properties Overview in The Objective-C 2.0 Programming Language.)