Objective-C運(yùn)行時(shí)的核心就在于消息分派器objc_msgSend
實(shí)現(xiàn)簡單的消息分派器。以下代碼用C編寫,為了證明Objective-C運(yùn)行時(shí)真的只是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);
}