skip to content

In Objective-C, what can a class extension add to a class that a category cannot, and what happens when two category methods share a name?

level: middleimportance: should knowfreq 55%

answer

  1. the empty parentheses in the .m
  2. storage needs the primary @implementation
  3. a category property gets no ivar
  4. undefined which implementation wins
  5. prefix methods on framework classes

basics

~20 s

A class extension can add instance variables and synthesized properties, because it compiles with the class's own @implementation; a category adds methods but no storage. When category methods clash with each other or the class, which one runs is undefined.

solid answer

~50 s

A **category**, `@interface NSString (PPFormatting)`, adds methods to any class, including framework classes, and those methods exist on every instance once the category is loaded. It cannot add an instance variable, so a property declared in a category gets no ivar and no synthesized accessors; clang warns that the accessors must be defined. A **class extension**, `@interface PPPrintOrder ()`, works only on a class you compile, its methods live in the primary `@implementation`, and its properties are synthesized with ivars, which is why it hosts private state and the `readwrite` redeclaration of a public `readonly` property. If two categories, or a category and the class, implement the same selector, Apple's guide says which one wins is undefined. Clang warns only when the class's own implementation is in the same file, so prefix category methods on framework classes, such as `pp_printLabel`.

code

objective-c · 31 lines
objective-c
#import <Foundation/Foundation.h>
#import <objc/runtime.h>

@interface PPPrintOrder : NSObject
@property (nonatomic, readonly, copy) NSString *orderID;
@end

// Class extension: compiled with the class, so it can add storage.
@interface PPPrintOrder ()
@property (nonatomic, readwrite, copy) NSString *orderID;
@property (nonatomic, strong) NSMutableArray<NSString *> *pendingPhotoIDs;
@end

@implementation PPPrintOrder
@end

// Category on a framework class: methods only, prefixed against clashes.
@interface NSString (PPFormatting)
@property (nonatomic, copy) NSString *pp_note;
- (NSString *)pp_printLabel;
@end

static const void *PPNoteKey = &PPNoteKey;

@implementation NSString (PPFormatting)
- (NSString *)pp_printLabel { return [self uppercaseString]; }
- (NSString *)pp_note { return objc_getAssociatedObject(self, PPNoteKey); }
- (void)setPp_note:(NSString *)note {
    objc_setAssociatedObject(self, PPNoteKey, note, OBJC_ASSOCIATION_COPY_NONATOMIC);
}
@end

go deeper

for a junior

Recall that a category adds methods to any class and a class extension in the .m holds private properties.

for a middle

Explain why only the extension can add synthesized storage, the readonly-to-readwrite pattern, and what a property in a category really gets.

for a senior

Diagnose a clash: undefined winner, framework methods added later, the missing compiler warning, and super not reaching the replaced method. Know associated objects and when to avoid them.

for a principal

Set the rules: prefixes on every framework-class category, no overriding through categories, and where private headers are allowed between related classes.

## Categories A **category** adds methods to an existing class without subclassing it. It has a name in parentheses and its own `@implementation`: ```objective-c @interface NSString (PPFormatting) - (NSString *)pp_printLabel; @end ``` Key properties of a category: - It works on **any class**, including Foundation and UIKit classes you have no source for. - Its methods become part of the class at run time, so every instance, including ones created by framework code, responds to them. - It can declare instance methods, class methods and protocol conformances. - It **cannot add instance variables**. Apple's guide states that a property declared in a category gets neither an ivar nor synthesized accessors; clang warns "property requires method to be defined - use @dynamic or provide a method implementation in this category". Calling such an accessor at run time raises "unrecognized selector". ## Class extensions A **class extension** looks like a category with empty parentheses, which is why it is also called an anonymous category: ```objective-c @interface PPPrintOrder () @property (nonatomic, readwrite, copy) NSString *orderID; @end ``` It can only extend a class whose source is compiled with it, because its methods must be implemented in the class's **primary** `@implementation`. In exchange it can do what a category cannot: - add **properties that are synthesized** with backing instance variables; - add instance variables declared in braces; - redeclare a public `readonly` property as `readwrite`, so only the class's own code can set it. Extensions usually sit at the top of the `.m` file to keep private state out of the header. A second header such as `PPPrintOrderPrivate.h` can share one with a few related classes, and only the public header ships with a framework. The privacy is a compile-time boundary. Apple's guide points out that redeclaring a property `readwrite` in an extension creates a setter that exists at run time on every instance, whether or not other files saw the extension; the compiler stops visible calls, but dynamic calls such as `performSelector:` still reach it. Design the public header so nobody needs to. ## Side by side | Capability | Category | Class extension | |---|---|---| | Works on framework classes | yes | no | | Adds methods | yes, in its own `@implementation` | yes, in the primary `@implementation` | | Adds synthesized properties and ivars | no | yes | | Has a name | yes | no | | Typical use | add behaviour, split a large class | private state and methods | ## Adding state to a category When a category truly needs per-object storage, the runtime offers **associated objects**: `objc_setAssociatedObject` and `objc_getAssociatedObject`, keyed by a unique `static` address and stored with a policy such as `OBJC_ASSOCIATION_COPY_NONATOMIC` or `OBJC_ASSOCIATION_RETAIN_NONATOMIC`. You write the accessors by hand in the category. When you own the class, a class extension property is simpler and easier to read. ## Name clashes Apple's guide is explicit: if a category method has the same name as a method in the original class, in another category on the same class, or even in a superclass, **the behaviour is undefined** as to which implementation is used at run time. Typical ways this happens: 1. Two linked libraries each add `base64EncodedString` to `NSString`; only one survives, and which one is not specified. 2. Your category adds a convenience that the framework later adds itself. Apple's example is `sortDescriptorWithKey:ascending:`, which `NSSortDescriptor` gained in iOS 4.0, colliding with categories that had added it earlier. 3. A category deliberately "overrides" a class method. Clang warns "category is implementing a method which will also be implemented by its primary class" when the class's own `@implementation` is in the same file, but a category on a framework class that redefines one of its methods compiles silently. A category method that replaces another also cannot call the method it displaced: `super` reaches the superclass, not the original implementation. That is why intentional replacement is done with method swizzling instead. ## Rules for a codebase - Prefix every method in a category on a class you do not own: lowercase prefix plus underscore, as in `pp_printLabel`. - Prefix the category name too, so categories from different libraries on one class stay distinguishable. - Never use a category to override an existing method. - Keep private properties in class extensions, not in categories with associated objects.

  • How do you give a category on a framework class a stored property?
    Declare the property in the category, then write both accessors yourself using `objc_getAssociatedObject` and `objc_setAssociatedObject` with a unique `static` key and a policy that matches the attributes, such as `OBJC_ASSOCIATION_COPY_NONATOMIC` for a `copy` string. Keep it rare: it hides state from the class's own code and from anyone reading its header.
  • Why doesn't a readonly header plus a readwrite class extension make a property truly private?
    The extension makes the synthesized setter exist on every instance at run time. The compiler stops other files from calling it because they never see the declaration, but any code can still reach it dynamically, for example with `performSelector:` or key-value coding. It is an interface boundary, not access control.
  • Why might a category method that has worked for years start misbehaving after an iOS update?
    The framework may have added a method with the same selector to the class. From then on two implementations exist and which one runs is undefined, so behaviour can differ by device or launch. Prefixing category methods on framework classes prevents the collision.

  • A category can add instance variables if you declare them in braces.
  • Properties declared in a category are synthesized like any other property.
  • A category method that replaces the class's method can call the original through super.
  • Class extensions can extend NSString or any other framework class.
  • Clang always warns when two categories define the same method.
  • The category linked last is guaranteed to win a name clash.