Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When & why do you use @interface ClassName (Private)? - Objective-C

I was looking at some code:

@interface ClassName (Private)

- (float)methodOne:(NSDictionary *)argOne;
- (void)methodTwo:(NSDictionary *)argTwo;

@end

@implementation ClassName
....

The above code is at the top of the ClassName.m file which appears to define additional interface methods for the class as private?

Why do this? what is the point? What else could go where (Private) is? Anyone have docs on this?

Thanks

like image 966
Mausimo Avatar asked Feb 01 '12 20:02

Mausimo


2 Answers

This is a way of keeping methods that the class uses internally from being exposed to others. It's part of encapsulation. In Objective-C 2.0 (iOS and Mac OS X 10.5+), it's more common to use a class extension at the top of the implementation file:

@interface ClassName ()

- (void)privateMethod;

@end

A class extension is really just a special case of a category (which is what you've asked about). The primary difference is that for a category, the compiler won't complain even if your @implementation doesn't include definitions for the methods declared in the category. For methods in a class extension, your class must implement those methods in its main @implementation block or you'll get a compiler warning.

You're better off using a class extension in iOS code or Mac code that targets at least Mac OS X 10.5 Leopard.

like image 152
Andrew Madsen Avatar answered Nov 14 '22 11:11

Andrew Madsen


Basically it is a category and allows adding methods in the .m file. These days the best way is to use a Class Extension, the syntax is similar just the "Private" is missing, just two parentheses.

The additional advantage of a class extension is that properties can also be included and the compiler will validate that all methods declared are defined.

One area that is really handy is the ability to declare a properly readonly in the .h file and read write in the .m file. That way users of the class only have read access but the class itself has full access.

like image 31
zaph Avatar answered Nov 14 '22 11:11

zaph