Apple Headers contain multiple Categories
While perusing some Apple Header files, I notice that they declare multiple interfaces using Categories for the same object.
For example: NSDictionary.h
@interface NSDictionary : NSObject <NSCopying, NSMutableCopying, NSC开发者_Go百科oding, NSFastEnumeration>
//methods
@end
@interface NSDictionary (NSExtendedDictionary)
//methods
@end
@interface NSDictionary (NSDictionaryCreation)
//methods
@end
Is this purely a way to help organize the code? As a user there is no difference, all methods in all Categories appear when utilizing a NSDictionary
.
Is there some other useful result of this?
nielsbot has the right idea, but there's a specific technical reason for the categories. You can put the implementations in separate files. (Well, different translation units technically speaking.)
File 1:
@implementation NSDictionary
...
@end
File 2:
@implementation NSDictionary (NSExtendedDictionary)
...
@end
File 3:
@implementation NSDictionary (NSDictionaryCreation)
...
@end
Pretty sure it's an organization thing. I am not aware of any other benefit of using Categories in a public header file. (They are of course useful for inserting new methods into existing classes)
EDIT: Check out Wikipedia. They seem to have a pretty authoritative answer:
During the design of Objective-C, one of the main concerns was the maintainability of large code bases. Experience from the structured programming world had shown that one of the main ways to improve code was to break it down into smaller pieces. Objective-C borrowed and extended the concept of categories from Smalltalk implementations to help with this process.[9]
from http://en.wikipedia.org/wiki/Objective-C#Categories
Seems to fit as well since the system headers came from NeXT--those are the guys that would write code in this fashion.
精彩评论