TExcelTAD
Home › Objective-C › Selectors & Dynamic Messaging

Selectors & Dynamic Messaging

A selector (type SEL) is the name of a method, turned into a value you can store, pass around and send later. Selectors are the foundation of the target–action pattern (buttons call action on target), of performSelector:, and of Objective-C's message forwarding.

Creating and performing selectors

objc · try it yourself
#import <Foundation/Foundation.h>

@interface Robot : NSObject
- (void)wave;
- (void)say:(NSString *)text;
- (void)move:(NSNumber *)steps direction:(NSString *)dir;
@end

@implementation Robot
- (void)wave { NSLog(@"*waves*"); }
- (void)say:(NSString *)text { NSLog(@"Robot says: %@", text); }
- (void)move:(NSNumber *)steps direction:(NSString *)dir {
    NSLog(@"moving %@ steps %@", steps, dir);
}
@end

int main(void) {
    @autoreleasepool {
        Robot *r = [Robot new];
        SEL greet = @selector(wave);

        [r performSelector:@selector(wave)];
        [r performSelector:@selector(say:) withObject:@"beep"];
        [r performSelector:@selector(move:direction:) withObject:@3 withObject:@"north"];

        NSLog(@"%@ / %@", NSStringFromSelector(greet), NSStringFromSelector(@selector(move:direction:)));
        NSLog(@"same selector? %d", sel_isEqual(greet, @selector(wave)));
    }
    return 0;
}
*waves*
Robot says: beep
moving 3 steps north
wave / move:direction:
same selector? 1

performSelector: and its variants take up to two object arguments. Pass the selector as a literal @selector(...) and the compiler knows which method you mean.

Note: If the selector is computed at run time ([r performSelector:someSel]), ARC warns "performSelector may cause a leak because its selector is unknown": it can't tell whether the method returns an object you need to release. Prefer literal selectors, blocks or protocols when you can.

Target–action

Store a target and a selector together and you get a configurable callback, the pattern behind every UIButton and NSTimer:

objc · try it yourself
#import <Foundation/Foundation.h>

@interface Button : NSObject
@property (nonatomic, copy) NSString *title;
@property (nonatomic, weak) id target;
@property (nonatomic) SEL action;
- (void)tap;
@end

@implementation Button
- (void)tap {
    if ([self.target respondsToSelector:self.action]) {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Warc-performSelector-leaks"
        [self.target performSelector:self.action withObject:self];
#pragma clang diagnostic pop
    }
}
@end

@interface Editor : NSObject
- (void)save:(Button *)sender;
- (void)undo:(Button *)sender;
@end

@implementation Editor
- (void)save:(Button *)sender { NSLog(@"saving (via '%@')", sender.title); }
- (void)undo:(Button *)sender { NSLog(@"undoing (via '%@')", sender.title); }
@end

int main(void) {
    @autoreleasepool {
        Editor *editor = [Editor new];
        NSMutableArray *toolbar = [NSMutableArray array];
        NSArray *specs = @[@[@"Save", @"save:"], @[@"Undo", @"undo:"], @[@"Print", @"print:"]];
        for (NSArray *spec in specs) {
            Button *b = [Button new];
            b.title = spec[0];
            b.target = editor;
            b.action = NSSelectorFromString(spec[1]);
            [toolbar addObject:b];
        }
        for (Button *b in toolbar) {
            NSLog(@"tap %@", b.title);
            [b tap];
        }
    }
    return 0;
}
tap Save
saving (via 'Save')
tap Undo
undoing (via 'Undo')
tap Print

The #pragma lines silence the leak warning for this one, deliberate case. In UIKit you'd write [button addTarget:editor action:@selector(save:) forControlEvents:UIControlEventTouchUpInside] and the framework does the rest.

What happens with an unknown message

Sending a message the object doesn't implement doesn't fail immediately. The runtime gives the object a few chances first:

  1. +resolveInstanceMethod: can add a method on the fly.
  2. -forwardingTargetForSelector: can name another object to receive the message.
  3. -forwardInvocation: can handle the message in any way.
  4. Only then is doesNotRecognizeSelector: called, which raises NSInvalidArgumentException ("unrecognized selector").

Step 2 is the easiest way to build a proxy:

objc · try it yourself
#import <Foundation/Foundation.h>

@interface Engine : NSObject
- (NSString *)ignite;
- (NSInteger)rpm;
@end
@implementation Engine
- (NSString *)ignite { return @"vroom"; }
- (NSInteger)rpm { return 3200; }
@end

@interface Car : NSObject
@property (nonatomic, strong) Engine *engine;
@end
@implementation Car
- (id)forwardingTargetForSelector:(SEL)sel {
    if ([self.engine respondsToSelector:sel]) {
        NSLog(@"(Car forwards %@ to its engine)", NSStringFromSelector(sel));
        return self.engine;
    }
    return [super forwardingTargetForSelector:sel];
}
@end

int main(void) {
    @autoreleasepool {
        Car *car = [Car new];
        car.engine = [Engine new];
        id anyCar = car;                       // id: the compiler allows any known selector

        NSLog(@"%@", [anyCar ignite]);
        NSLog(@"%ld rpm", (long)[anyCar rpm]);

        @try {
            [anyCar uppercaseString];          // nobody handles this one
        } @catch (NSException *e) {
            NSLog(@"caught %@", e.name);
        }
    }
    return 0;
}
(Car forwards ignite to its engine)
vroom
(Car forwards rpm to its engine)
3200 rpm
caught NSInvalidArgumentException

Car doesn't implement ignite or rpm, yet the messages work: the runtime asked Car for a forwarding target and resent them to the engine.

Selectors as data: a command table

objc · try it yourself
#import <Foundation/Foundation.h>

@interface Shell : NSObject
- (NSString *)cmdHelp;
- (NSString *)cmdDate;
- (NSString *)cmdVersion;
- (NSString *)run:(NSString *)command;
@end

@implementation Shell
- (NSString *)cmdHelp { return @"commands: help, date, version"; }
- (NSString *)cmdDate { return @"2026-01-15"; }
- (NSString *)cmdVersion { return @"shell 1.0"; }
- (NSString *)run:(NSString *)command {
    NSString *name = [@"cmd" stringByAppendingString:[command capitalizedString]];
    SEL sel = NSSelectorFromString(name);
    if (![self respondsToSelector:sel]) {
        return [NSString stringWithFormat:@"unknown command: %@", command];
    }
    NSString *(*impl)(id, SEL) = (void *)[self methodForSelector:sel];   // the method's C function
    return impl(self, sel);
}
@end

int main(void) {
    @autoreleasepool {
        Shell *sh = [Shell new];
        for (NSString *cmd in @[@"help", @"version", @"date", @"reboot"]) {
            NSLog(@"$ %@ -> %@", cmd, [sh run:cmd]);
        }
    }
    return 0;
}
$ help -> commands: help, date, version
$ version -> shell 1.0
$ date -> 2026-01-15
$ reboot -> unknown command: reboot

methodForSelector: returns the method's implementation (an IMP, a plain C function pointer whose first two arguments are self and the selector). Calling it directly is type-safe and avoids the performSelector: warning. Every Objective-C method is, underneath, such a C function.

Test yourself

What is a selector?

  1. A pointer to an object
  2. The name of a method, usable as a value
  3. A block
  4. A class object

What does forwardingTargetForSelector: let an object do?

  1. Rename a method
  2. Hand an unhandled message to another object
  3. Delete a method
  4. Make a method private

What exception results when no object handles a message?

  1. NSRangeException
  2. NSInvalidArgumentException (unrecognized selector)
  3. NSMallocException
  4. No exception: it returns nil