How does message passing work in Objective-C?
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