4. Categories
• Extend classes without subclassing.
• Create informal protocols.
• Spread implementation over multiple files.
• Simply development when multiple
programmers are working on the same file.
• Fix bugs in classes when you don’t have
access to the source (in a last resort).
5. Some Cocoa classes
are “class clusters” so
subclassing is very
difficult (NSString,
NSArray, etc).
6. Sometimes, Apple uses
“informal protocols.”
(categories with no
implementation)
-(void)awakeFromNib;
7. (Maybe this is
obsolete.)
@protocol MyProtocol
@optional:
-(void)thisMethod;
-(void)thatMethod;
@end
8. Anonymous Categories
are like private
methods.
@implementation MyClass()
-(void)methodThatIWantToBePrivate;
@end
9. But not really.
(The Objective-C runtime isn’t that secure.)
@implementation MyClass()
-(void)methodThatIWantToBePrivate;
@end
// in another class
MyClass *myClass = [[MyClass alloc] init];
[myClass methodThatIWantToBePrivate]; // calls it
10. Be Careful About
• Overriding existing methods
• Causing conflicts with other categories (if
two categories implement the method with
the same name, the result is on predictable)
11. 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
12. One example when I use categories is
using Core Data. Core Data will auto
generate class files.
If I want to add methods to those
classes, I add them in a category so that, if
I need to regenerate the classes, they
won’t overwrite my changes.