Objective-C运行时的核心就在于消息分派器objc_msgSend
实现简单的消息分派器。以下代码用C编写,为了证明Objective-C运行时真的只是C。
static const void *myMsgSend(id receiver, const char *name) {
SEL selector = sel_registerName(name);
IMP methodIMP = class_getMethodImplementation(object_getClass(receiver), selector);
return methodIMP(receiver, selector);
}
void RunMyMsgSend() {
// NSObject *object = [[NSObject alloc] init];
Class class = (Class)objc_getClass("NSObject");
id object = class_createInstance(class, 0);
myMsgSend(object, "init");
// id description = [object description];
id description = (id)myMsgSend(object, "description");
// const char * cstr = [description UTF8String];
const char *cstr = myMsgSend(description, "UTF8String");
printf("%s\n",cstr);
}