gpt4 book ai didi

ios - ObjC class_addMethod 不检查参数类型?

转载 作者:行者123 更新时间:2023-12-01 22:18:33 29 4
gpt4 key购买 nike

#import <objc/runtime.h>

@implementation Foo

+ (void)test
{
[Foo performSelector:@selector(foo)];
[Foo performSelector:@selector(foo) withObject:@"works"];
[Foo performSelector:@selector(foo1)];
[Foo performSelector:@selector(foo2)];
}

+ (BOOL)resolveClassMethod:(SEL)sel
{
NSLog(@"resolveClassMethod: %@", NSStringFromSelector(sel));
if (sel == @selector(foo)) {
class_addMethod(objc_getMetaClass("Foo"), sel, (IMP)fooIMP_withoutArgument, "s@#@@@");
return YES;
} else if (sel == @selector(foo1)) {
class_addMethod(objc_getMetaClass("Foo"), sel, (IMP)fooIMP_with1Argument, "Works");
return YES;
} else if (sel == @selector(foo2)) {
class_addMethod(objc_getMetaClass("Foo"), sel, (IMP)fooIMP_with2Arguments, "Not Works");
return YES;
}
return [super resolveClassMethod:sel];
}

void fooIMP_withoutArgument(id self, SEL _cmd)
{
NSLog(@"fooIMP_withoutArgument");
}

void fooIMP_with1Argument(id self, SEL _cmd, id arg)
{
NSLog(@"fooIMP_with1Argument");
}

void fooIMP_with2Arguments(id self, SEL _cmd, id arg1, id arg2)
{
NSLog(@"fooIMP_with2Argument");
}

@end

输出是:
2018-02-27 16:41:31.638693+0800 Test[74840:2194481] resolveInstanceMethod: foo
2018-02-27 16:41:31.639201+0800 Test[74840:2194481] fooIMP_withoutArgument
2018-02-27 16:41:31.639228+0800 Test[74840:2194481] fooIMP_withoutArgument
2018-02-27 16:41:31.639490+0800 Test[74840:2194481] resolveInstanceMethod: foo1
2018-02-27 16:41:31.639519+0800 Test[74840:2194481] fooIMP_with1Argument
2018-02-27 16:41:31.639548+0800 Test[74840:2194481] resolveInstanceMethod: foo2
(lldb)
  • class_addMethod函数不检查参数类型?
  • 选择器是否只是实现的关键点而没有其他角色?
  • 为什么IMP有 1 个参数有效,但 2 个参数无效?
  • 调用带参数(或不带参数)但不带参数(或有)的 IMP 的方法时如何工作

  • 有人可以帮我解释原因吗?

    最佳答案

    class_addMethod function does not check argument types?



    它不是。作为一种动态类型语言,Objective-C 本质上都只是 id在运行时——对象的类型检查发生在编译时,并且该信息不会保存在二进制文件中。 class_addMethod是一个低级运行时函数,因此它不包括任何类型检查。没关系,因为这些运行时函数很少使用,并且仅在您确切知道自己在做什么以及因此期望什么类型的情况下才使用。

    SEL is just a key point to IMP without other role?


    SEL是一个选择器,在 Objective-C 的典型实现中是一个字符串,在引擎盖下。 objc_msgSend将此选择器解析为 IMP ,这只是一个函数,其主体包含方法的实现。

    Why IMP with 1 argument work, but 2 arguments not?



    由于您没有向我们展示 foo2 的签名,也不描述到底出了什么问题,很难说。但是由于您似乎没有尝试调用 foo2有了任何论据,结果最终会成为您想要的东西并不奇怪。

    此外,您不会返回 YES添加方法后,但调用 superresolveInstanceMethod: 的实现.如果该方法恰好返回 NO ,运行时会认为添加该方法不起作用。您应该返回 YES而是在成功添加方法后。 (如果你不这样做,你应该调用 superresolveClassMethod: 而不是 resolveInstanceMethod: 的实现。)

    关于ios - ObjC class_addMethod 不检查参数类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49003493/

    29 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com