methodForSelector 和 instanceMethodForSelector

xiaoxiao2021-02-28  97

使用方法:

- (void)testIMP

{

    //1. 实例方法无参数

    TestClass *adapt = [[TestClassalloc] init];

    SEL sel =@selector(test);

    IMP imp = [adaptmethodForSelector:sel];

    void (*func)(__strongid,SEL) = (void (*)(__strongid, SEL))imp;

    func( adapt,  sel);

    

    //2. 实例方法有参数

    NSString *param =@"AAA";

    sel = @selector(test2:);

    imp = [adapt methodForSelector:sel];

    void (*func2)(__strongid,SEL,NSString*) = (void (*)(__strongid, SEL,NSString*))imp;

    func2( adapt,  sel, param);

    

    //3. 实例方法有参数

    imp = [TestClassinstanceMethodForSelector:sel];

    void (*func3)(__strongid,SEL,NSString*) = (void (*)(__strongid, SEL,NSString*))imp;

    func3(adapt, sel, param);

    

    //4. 类方法

    sel = @selector(test3);

    imp = [TestClassmethodForSelector:sel];

    void (*func4)(__strongid,SEL) = (void (*)(__strongid, SEL))imp;

    func4(nil, sel);

}

- (void)test

{

    NSLog(@"---test");

}

    

- (void)test2:(NSString*)str

{

    NSLog(@"---test2:%@", str);

}

+ (void)test3

{

    NSLog(@"---test3");

}

区别:

methodForSelector:

If the receiver is an instance, aSelector should refer to an instance method; 

if the receiver is a class, it should refer to a class method.

instanceMethodForSelector:

Use this method to ask the class object for the implementation of instance methods only. 

To ask the class for the implementation of a class method, send the methodForSelector: instance method to the class instead.

    

转载请注明原文地址: https://www.6miu.com/read-39373.html

最新回复(0)