Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why Declare a Category in Same Header File as Class Declaration

Tags:

objective-c

After poking around some header files in the Foundation framework (NSString.h for example), I noticed that the declaration for NSString looks like:

@interface NSString : NSObject <NSCopying, NSMutableCopying, NSSecureCoding>

/* NSString primitive (funnel) methods. A minimal subclass of NSString just needs to implement these, although we also recommend getCharacters:range:. See below for the other methods. */
- (NSUInteger)length;           
- (unichar)characterAtIndex:(NSUInteger)index;

@end

The rest of the methods are declared in categories, which in turn are declared in the same header file.

After reading this answer, the implication seems to be mostly for organizing code.

Is there a benefit (other than logical grouping of methods) to declaring categories in the same header as the class declaration, especially in the case where the implementation is hidden, as in the case of NSString?

like image 533
Mike D Avatar asked May 31 '13 19:05

Mike D


1 Answers

Generally, yes, categories are used for organisational purposes. But in the case of NSString they are mainly used because NSString is a class cluster. As such, the categories are used to define the additional methods (as opposed to the primitive methods) of the classes in the cluster.

There's a nice write up about class clusters from Mike Ash here.

like image 140
Wain Avatar answered Oct 06 '22 02:10

Wain