What are categories and class extensions?
Category
@interface NSString (Validation) adds methods to an existing class without subclassing, including system classes and those whose source you do not have. The category's methods are merged into the class's method table at load time and are visible to all instances.
Limits and traps:
- You cannot add an ivar; a
@propertyin a category declares only the accessors, and storage has to go through associated objects. - If a category declares a method the class already has, it replaces it, and which of two categories wins is undefined. That is why category methods are conventionally prefixed (
ds_trimmed). - A category cannot call the "original" — swizzling exists for that.
- Category methods from a static library may fail to link without
-ObjC/-all_load.
#import <Foundation/Foundation.h>
#import <objc/runtime.h>
@interface NSObject (Tag)
@property (nonatomic, copy) NSString *ds_tag;
@end
@implementation NSObject (Tag)
static char kTagKey;
- (NSString *)ds_tag {
return objc_getAssociatedObject(self, &kTagKey);
}
- (void)setDs_tag:(NSString *)tag {
objc_setAssociatedObject(self, &kTagKey, tag,
OBJC_ASSOCIATION_COPY_NONATOMIC);
}
@end
The rest of this answer, with code and interview follow-ups, is in the DevPrep app.
Read the full answer in DevPrep