Categories• Extend classes without subclassing.• Create informal protocols.• Spread implementation over multiple ﬁles.• Simply development when multiple programmers are working on the same ﬁle.• Fix bugs in classes when you don’t have access to the source (in a last resort).
Some Cocoa classesare “class clusters” so subclassing is very difﬁcult (NSString, NSArray, etc).
Sometimes, Apple uses “informal protocols.” (categories with no implementation)-(void)awakeFromNib;
(Maybe this is obsolete.)@protocol MyProtocol@optional:-(void)thisMethod;-(void)thatMethod;@end
Anonymous Categories are like private methods.@implementation MyClass()-(void)methodThatIWantToBePrivate;@end
But not really. (The Objective-C runtime isn’t that secure.)@implementation MyClass()-(void)methodThatIWantToBePrivate;@end// in another classMyClass *myClass = [[MyClass alloc] init];[myClass methodThatIWantToBePrivate]; // calls it
Be Careful About• Overriding existing methods• Causing conﬂicts with other categories (if two categories implement the method with the same name, the result is on predictable)
Subclassing vs Categories• Many times, the difference is not clear-cut• Subclass when you need to add a property (but in iOS 5 categories can add properties)• Don’t subclass Class Clusters
One example when I use categories is using Core Data. Core Data will auto generate class ﬁles. If I want to add methods to thoseclasses, I add them in a category so that, if I need to regenerate the classes, they won’t overwrite my changes.