DevPrep

All topics › Objective-C

What are categories and class extensions?

Middle PRO

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:

#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

Practice this before your interview

DevPrep turns these answers into one-minute challenges: what does this code print, find the bug, mock interviews. One challenge a day.

Get DevPrep on the App Store