9. Instance of Example Class Example Metaclass Example
isa isa
Class BaseExample
isa
Class NSObject
isa
Metaclass
BaseExample
Metaclass NSObject
super_class
super_class
super_class
super_class
Class hierarchy
10. struct objc_method {
SEL method_name; // signature of method
char *method_types; // types of the parameters to the method
IMP method_imp; // memory address of the start of code block
};
typedef struct objc_method *Method;
A selector is the name used to select a method to execute for an object, or the
unique identifier that replaces the name when the source code is compiled.
Selector – C-string;
IMP - typedef id (*IMP)(id self,SEL _cmd,...);
Method
11. NSString *result = [example execWithParam:@"param"];
id objc_msgSend(id self, SEL op, ...)
result = objc_msgSend(example, @selector(execWithParam:), @"param");
Tail-call: typedef id (*IMP)(id self,SEL _cmd,...);
void objc_msgSend(void /* id self, SEL op, ... */ )
NSString *result = ((NSString* (*)(id, SEL, NSString *))objc_msgSend)(example,
@selector(execWithParam:), @"param");
Sending Messages
12. id objc_msgSend(id self, SEL op, ...)
Sends a message with a simple return value to an instance of a class.
double objc_msgSend_fpret(id self, SEL op, ...)
Sends a message with a floating-point return value to an instance of a class.
void objc_msgSend_stret(void * stretAddr, id theReceiver, SEL theSelector, ...)
Sends a message with a data-structure return value to an instance of a class.
id objc_msgSendSuper(struct objc_super *super, SEL op, ...)
Sends a message with a simple return value to the superclass of an instance of a class.
void objc_msgSendSuper_stret(struct objc_super *super, SEL op, ...) Sends a message with a
data-structure return value to the superclass of an instance of a class.
objc_msgSend
14. resolveInstanceMethod
1. Class cache -> class dispatch table -> all super classes
2. resolveInstanceMethod for @dynamic properties
id dynamicGetter(id self, SEL _cmd);
void dynamicSetter(id self, SEL _cmd, id value);
+ (BOOL)isDynamicProperty:(NSString *)selectorString;
+ (BOOL)resolveInstanceMethod:(SEL)sel {
NSString *selectorString = NSStringFromSelector(sel);
if ([self isDynamicProperty:selectorString]) {
if ([selectorString hasPrefix:@"set"]) {
class_addMethod(self, sel, (IMP)dynamicSetter, "v@:@");
} else {
class_addMethod(sel, sel, (IMP)dynamicGetter, "@@:");
}
return YES;
}
return [super resolveInstanceMethod:sel];
}
// "v@:@", "@@:" - Objective-C type encodings
15. forwardingTargetForSelector
3. The Runtime then calls forwardingTargetForSelector
Returns the object to which unrecognized messages should first be directed.
- (id)forwardingTargetForSelector:(SEL)aSelector {
if (aSelector == @selector(magicMethod:)) {
return magicObject;
} else {
return [super forwardingTargetForSelector:aSelector];
}
}