我是 Objective-C 的新手,我有一些问题:
什么是 IMP?
什么是msgSend函数?
最佳答案
IMP 是一个实现指针,它基本上是确定在收到消息(如 foo length)后运行的内容的钩子(Hook)。通常你不需要它们,除非你心情不好或者脏兮兮的。处理选择器通常更容易。
6.1 What is an IMP ?
It's the C type of a method implementation pointer, a function
pointer to the function that implements an Objective-C method. It is defined to return id and takes two hidden arguments, self and _cmd :
typedef id (*IMP)(id self,SEL _cmd,...); 6.2 How do I get an IMP given a SEL ? This can be done by sending a methodFor: message : IMP myImp = [myObject methodFor:mySel]; 6.3 How do I send a message given an IMP ? By dereferencing the function pointer. The following are all equivalent : [myObject myMessage]; or IMP myImp = [myObject methodFor:@selector(myMessage)]; myImp(myObject,@selector(myMessage)); or [myObject perform:@selector(myMessage)];
摘自 Objective C FAQ 的第 6.1 节.
至于 msgSend,这是在另一个对象上调用远程消息的方式; objc_msgSend(foo,@selector(bar)) 与 [foo bar] 大致相同。但这些都是底层的实现细节;您很少(如果有的话)需要使用 Objective C 代码的扩展调用,因为您可以使用 @selector 来获取方法并执行 PerformSelector: 在任何对象上调用它。
关于Objective-C 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1192614/