Skip to content
Tutorials Center
My learning

Topics

Lesson 26 of 38 ยท Protocols, Categories and Blocks

Categories and Class Extensions

Add methods to existing Objective-C classes with categories, hide private details with class extensions, learn associated objects, naming rules and the pitfalls of overriding methods.

Most languages make you subclass to add behavior. Objective-C offers something lighter: a category adds methods to an existing class, even one you do not own and cannot see the source of, such as NSString. Its sibling, the class extension, adds private declarations to a class you are writing. Both are cornerstones of how Cocoa code is organized.

Categories

A category is declared with the class name followed by a name in parentheses:

OBJECTIVEC
// NSString+Slug.h
@interface NSString (Slug)
- (NSString *)slugified;
@end

// NSString+Slug.m
@implementation NSString (Slug)
- (NSString *)slugified {
    NSString *lower = [self lowercaseString];
    NSArray *parts = [lower componentsSeparatedByCharactersInSet:
        [[NSCharacterSet alphanumericCharacterSet] invertedSet]];
    NSPredicate *nonEmpty = [NSPredicate predicateWithFormat:@"length > 0"];
    return [[parts filteredArrayUsingPredicate:nonEmpty] componentsJoinedByString:@"-"];
}
@end

Import the header and every NSString, including literals and existing mutable strings, responds to slugified:

OBJECTIVEC
NSLog(@"%@", [@"Hello, Objective-C World!" slugified]);   // hello-objective-c-world

The method is added to the class at runtime, so it works for objects that already exist and for subclasses. Typical uses:

  • Extending framework classes with helpers (NSDate+Formatting, UIColor+Hex).
  • Splitting a large class across several files, each category handling one concern.
  • Grouping protocol implementations, such as a Person (Printing) category implementing NSCopying.

File naming convention: ClassName+CategoryName.h/.m.

Rules and limits

  • A category can add methods, but not instance variables. Properties declared in a category get no automatic backing storage (see associated objects below).
  • Category methods are global to the class. If two categories (or a category and the class) define the same method name, which one wins is undefined. Avoid overriding a class's own methods from a category.
  • Give methods on classes you do not own a prefix (xyz_slugified) so they cannot collide with a method Apple adds later.
  • Linking static libraries that contain only categories may need the -ObjC linker flag so the category code is loaded.

Class extensions

A class extension looks like a category with no name. It is declared in the .m file, and it can add instance variables, properties and private methods:

OBJECTIVEC
// Account.h : the public face
@interface Account : NSObject
@property (nonatomic, readonly) double balance;
- (void)deposit:(double)amount;
@end

// Account.m : private implementation details
@interface Account ()
@property (nonatomic, readwrite) double balance;     // writable inside only
@property (nonatomic, strong) NSMutableArray *ledger; // private state
- (void)recordEntry:(NSString *)text;                 // private method
@end

@implementation Account
- (void)deposit:(double)amount {
    self.balance += amount;
    [self recordEntry:[NSString stringWithFormat:@"deposit %.2f", amount]];
}
- (void)recordEntry:(NSString *)text {
    if (!self.ledger) self.ledger = [NSMutableArray array];
    [self.ledger addObject:text];
}
@end

Because the compiler sees the extension before the @implementation, the methods are checked and stored properly. Use extensions for anything you would mark private in another language, since Objective-C has no private method keyword. (Instance variables do support @private, @protected, @public, but properties in an extension are the modern way.)

Category Class extension
Name (Name) ()
Adds ivars/properties with storage No Yes
Source needed No Yes (same module)
Typical file Class+Name.h/.m the class's own .m
Purpose Extend any class, split code Private API of your own class

Informal protocols and categories on NSObject

Before @optional existed, delegate methods were declared as a category on NSObject (an informal protocol). You still see this in older frameworks. Modern code uses formal protocols.

Associated objects

Since a category cannot add instance variables, you can attach data to an object at runtime with the associated object API:

OBJECTIVEC
#import <objc/runtime.h>

static const void *kTagKey = &kTagKey;

@interface NSObject (Tagging)
@property (nonatomic, copy) NSString *tag;
@end

@implementation NSObject (Tagging)
- (void)setTag:(NSString *)tag {
    objc_setAssociatedObject(self, kTagKey, tag, OBJC_ASSOCIATION_COPY_NONATOMIC);
}
- (NSString *)tag {
    return objc_getAssociatedObject(self, kTagKey);
}
@end

The runtime stores the value in a side table keyed by the object and the key pointer. It is powerful and easy to abuse, so use it sparingly. More on the machinery in the runtime lesson.

A model: adding behavior to something you do not own

The C stand-in below has a pre-existing String type with a fixed method table. A "category" is a function that registers a new entry in the table at startup, and a side table plays the role of associated objects.

C Stand-in: a category adds a method to an existing type

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

The existing String value gained a method without any change to its definition, which is exactly what a category does to existing NSString instances.

Safe habits

  • Prefer a category over a subclass for pure convenience helpers.
  • Prefix methods on framework classes; never override framework methods in a category.
  • Put private properties and methods in a class extension, not in the public header.
  • Keep each category focused, and name the file after it.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What can a category NOT add to a class?

    Categories add methods only. Use a class extension (with source) or associated objects for state.
  2. 2. Where is a class extension normally written?

    An unnamed category in the implementation file declares private properties and methods.
  3. 3. Why prefix category method names on framework classes?

    Method name collisions between categories and classes have an unpredictable winner.
  4. 4. How can a category store a value per object?

    Associated objects keep a runtime side table keyed by object and key.

Summary

  • A category adds methods to any existing class, even without its source.
  • A class extension adds private properties, ivars and methods to your own class.
  • Avoid name collisions: prefix methods and never override class methods from a category.
  • Associated objects fake stored properties in categories; use them rarely.

Next: Blocks