Objective-C 中怎么通过imp获得sel
时间: 2024-03-18 10:42:29 浏览: 70
可以使用 `method_getName` 函数从 `Method` 对象中获取对应的 `SEL` 选择器,然后通过 `sel_getName` 函数将 `SEL` 类型的选择器转换为 C 字符串。
具体的实现方式如下:
```objective-c
- (void)testMethod {
IMP imp = [self methodForSelector:@selector(testMethod)];
Method method = class_getInstanceMethod([self class], @selector(testMethod));
SEL sel = method_getName(method);
const char *selName = sel_getName(sel);
NSLog(@"SEL为:%s", selName);
}
```
需要注意的是,如果 `IMP` 指向的函数与给定的 `SEL` 选择器不匹配,则可能导致未定义的行为。因此,建议先获取 `Method` 对象,再从中获取 `SEL` 选择器。
相关问题
Objective-C 中怎么获得调用者的imp
在 Objective-C 中,要获得调用者的 IMP指向方法实现的指针),可以使用 `method_getImplementation` 函数。这个函数可以从方法选择器和类中获取方法的实现。
以下是一个示例代码,展示了如何获取调用者的 IMP:
```objc
#import <objc/runtime.h>
void calleeMethod() {
// 获取调用者的方法选择器
SEL callerSelector = NSSelectorFromString(@"callerMethod");
// 获取调用者的类
Class callerClass = [NSObject class]; // 替换成实际的调用者类
// 获取调用者的方法
Method callerMethod = class_getInstanceMethod(callerClass, callerSelector);
// 获取调用者的 IMP
IMP callerIMP = method_getImplementation(callerMethod);
NSLog(@"Caller IMP: %p", callerIMP);
}
void callerMethod() {
calleeMethod();
}
int main() {
callerMethod();
return 0;
}
```
在上述示例代码中,我们定义了两个方法 `callerMethod` 和 `calleeMethod`。在 `calleeMethod` 中,我们使用 `class_getInstanceMethod` 函数获取 `callerMethod` 的方法结构体,然后使用 `method_getImplementation` 函数获取 `callerMethod` 的 IMP。最后,我们通过打印输出来显示调用者的 IMP。
请注意,上述示例代码中的调用者类是一个简单的示例,您需要将其替换为实际的调用者类。
总结而言,您可以使用 `method_getImplementation` 函数来获取调用者的 IMP。请根据您的具体需求和代码结构,将示例代码中的调用者方法和类替换为实际的情况。
希望这可以解决您的问题。如有更多疑问,请随时提问。
Objective-C类方法调用时怎么找到相应的imp
在Objective-C中,类方法是属于类的,而不是属于实例的。当我们调用一个类方法时,实际上是通过类对象来调用的。每个类对象都有一个isa指针,指向它的元类对象。元类对象中维护了类方法的列表,列表中存储了每个类方法的名称和对应的实现函数指针(IMP)。
当我们调用一个类方法时,会首先在类对象的元类对象中查找该方法的实现函数指针(IMP),如果找到了就直接调用该函数;如果没有找到,就会在父类的元类对象中查找,直到找到NSObject类的元类对象为止。如果最终还是没有找到,就会触发`+ (void)doesNotRecognizeSelector:(SEL)aSelector`方法,抛出一个`NSInvalidArgumentException`异常。
因此,当我们在子类中实现一个类方法时,如果该类方法与父类中的同名类方法不同,就会覆盖父类的实现。如果我们想在子类中调用父类的同名类方法,可以使用`super`关键字来调用父类的实现。
阅读全文
相关推荐
















