Wednesday, April 25, 2012

Objective-C. Class Extensions.

Few years ago, I was writing my first program in Objective-C, I was surprised that there is no way to add a private method to my class. Encapsulation, one of the basic principles of the OO programming, does not work in Objective-C? Unbelievable.
I found a way to declare a private category in the class main implementation class:

@interface MyClass (Private)
- (void)privateMethod;
@end

Once, by mistake, probably because of this annoying spell checker helping to type code in Xcode, I forgot the category name:


@interface MyClass ()
- (void)privateMethod;
@end

 I thought it's a bug in the compiler. I decided to not use this way - one day the bug will be fixed. Than, in the github I found a few programs using this way (the category without a name), moreover, people declare instance variables in such anonymous category.

I found the explanation in iOS Developer Library:
Categories and Extensions 

Objective-C 2.0 has a mechanism allowing to add private methods and private variables to a class (the encapsulation in Objective-C is on the highest level). The name of the feature is Class Extensions.
Class Extensions is a great place to redeclare a property publicly declared as read only - in the extension the property can be redeclared with the read-write attribute.

No comments:

Post a Comment