Reading — step 1 of 5
Learn
~1 min readCategories and Protocols
A category adds methods to an existing class — even one you don't own — without subclassing.
#import <Foundation/Foundation.h>
@interface NSString (Reversed)
- (NSString *)reversed;
@end
@implementation NSString (Reversed)
- (NSString *)reversed {
NSMutableString *result = [NSMutableString stringWithCapacity:self.length];
for (NSInteger i = self.length - 1; i >= 0; i--) {
[result appendFormat:@"%C", [self characterAtIndex:i]];
}
return result;
}
@end
// Now ANY NSString has -reversed:
NSString *s = @"hello";
NSString *rev = [s reversed]; // "olleh"
The (Reversed) after the class name is the category name — purely descriptive.
Use cases:
- Add convenience methods to UIKit/Foundation classes
- Group related methods of a large class across files
- Provide platform-specific implementations
Caveats:
- Can't add instance variables in a category (only methods)
- If two categories define the same method, behavior is undefined
- Method calls go through dynamic dispatch (no compile-time check across categories)
Class extensions — anonymous categories (), used inside the class's own .m file to declare "private" methods/properties:
@interface MyClass () // class extension — no name
@property NSInteger internalCount;
- (void)privateHelper;
@end
Anything declared in a class extension is part of the class itself — but only visible in that file.
Discussion
Ask a question, share an insight, or help someone who’s stuck.
Sign in to post a comment or reply.
Loading…