DevPrep

All topics › Objective-C

How does message passing work in Objective-C?

Middle PRO

Essence

In Objective-C [obj greet:name] is not a function call but a message send. The compiler does not know which code will run: it packs the receiver, the selector (@selector(greet:), a unique name string of the method) and the arguments into a call to objc_msgSend. Which implementation (IMP) runs is decided at call time by the receiver's class — this is late binding.

#import <Foundation/Foundation.h>

@interface Greeter : NSObject
- (NSString *)greet:(NSString *)name;
@end

@implementation Greeter
- (NSString *)greet:(NSString *)name {
    return [NSString stringWithFormat:@"Hi, %@", name];
}
@end

static NSString *demo(Greeter *g) {
    // the compiler turns this into
    // objc_msgSend(g, @selector(greet:), @"Ann")
    return [g greet:@"Ann"];
}

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