methodForSelector 和 instanceMethodForSelector

本文详细介绍了在Objective-C中如何通过方法解析器获取并直接调用实例方法及类方法,包括无参和带参的方法,并对比了methodForSelector与instanceMethodForSelector的区别。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

使用方法:

- (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.


    


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值