I’m seeing some code I’ve inherited that looks like the following:
@interface SomeClass (private)
This is within SomeClass.m, the implementation file. There is an accompanying header file which doesn’t suggest that the class is using a category. Is (private) in this case just a poor name given to a category for SomeClass? And I’m assuming it’s perfectly legitimate to specify categories such as these in an implementation?
It isn’t the name ‘private’ that makes it private; the methods are private because they are in a category declared within the implementation file.
There are three uses of a category, each of which add methods to a class (note: methods only, not iVars)
Extending an existing Cocoa class
This lets you add your own methods to an existing class. For example, if you want to extend NSString to apply special capitalization, you could create a new class called, say NSString+Capitals. in the NSString+Capitals.h you would have:
and in NSString+Capitals.m you would implement the method
Private methods on a class
This is the same as above, except that the extra methods are declared and defined in the implementation file (.m) Usually a way of having private methods – because they are not in the .h file (which is the one #imported by other classes) they are simply not visible. In this case, the implementation of the methods are done in their own implementation block. e.g
Class Extension (New for 10.5 Leopard)
A simpler way of having private methods. In this special case, the category name is empty and the private methods are implemented in the same block as all the other class methods.
Here’s a link to the Apple docs on Categories and extensions.