【问题标题】:iOS invoke class method with IMPiOS 用 IMP 调用类方法
【发布时间】:2017-05-01 22:54:21
【问题描述】:

假设我正在开发一个调整应用程序,我想创建一个无法导入标头的类的实例,但我知道类名、类方法和实例方法如何在带参数的类方法中创建它? 用类方法说这个类叫做 MMClass

  +(instancetype)do:(NSString*)string for:(NSString *)antherString; 

我正在做的事情如下:

Class class = objc_getClass("MMClass");
Method initMethod = class_getClassMethod(class,
                                             @selector(do:for:));
IMP imp = method_getImplementation(initMethod);
id instance = imp(class,@selector(do:for:),@"do",@"ye");

这样对吗?

【问题讨论】:

    标签: ios class methods tweak


    【解决方案1】:

    首先,我不确定我是否在说明显而易见的事情,但为什么不使用您要使用的声明创建您自己的标题并导入它(或者如果您只在文件顶部内联声明只会在一个文件中使用它)?并正常调用方法?而不是经历所有这些混乱?编译器所关心的只是它看到了你想要调用的方法的一些声明。

    当你使用函数指针调用实际的方法实现时,你需要将它转换为与方法签名对应的正确类型的函数指针:

    Class class = objc_getClass("MMClass");
    Method initMethod = class_getClassMethod(class, @selector(do:for:));
    IMP imp = method_getImplementation(initMethod);
    id (*foo)(Class, SEL, NSString *, NSString *) =
        (id (*)(Class, SEL, NSString *, NSString *))imp;
    id instance = foo(class, @selector(do:for:), @"do", @"ye");
    

    但是获得一个你只会使用一次的 IMP 是很愚蠢的。相反,您应该将 objc_msgSend 转换为所需的函数指针类型,然后直接调用它:

    Class class = objc_getClass("MMClass");
    id (*foo)(Class, SEL, NSString *, NSString *) =
        (id (*)(Class, SEL, NSString *, NSString *))objc_msgSend;
    id instance = foo(class, @selector(do:for:), @"do", @"ye");
    

    【讨论】:

    • 抱歉回复晚了,谢谢
    猜你喜欢
    • 2012-07-31
    • 2017-02-28
    • 2011-11-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多