oc methodForSelector与instanceMethodForSelector区别

- (IMP)methodForSelector:(SEL)aSelector
如果接受者是一个类对象,则返回类对象的方法;
如果接受者是一个实例对象,则返回实例对象的方法;
+ (IMP)instanceMethodForSelector:(SEL)aSelector
返回一个对应aSelector的实例方法
下面是个demo
#import <Foundation/Foundation.h>

@interface ATest : NSObject
@property (nonatomic, strong) NSDictionary *hiDIc;
- (void)sayHi;
+ (void)sayHi;
@end

#import "ATest.h"

@implementation ATest
- (void)sayHi{
    NSLog(@"instance say hi=%@;",self.hiDIc);
}
+ (void)sayHi{
    NSLog(@"class say hi");
}
@end

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        // insert code here...
        NSLog(@"Hello, World!");
        ATest *test = [[ATest alloc]init];
        test.hiDIc = @{};
        SEL sel = NSSelectorFromString(@"sayHi");
        IMP mp = [test methodForSelector:sel];
        void(*mp1)(id,SEL) = (void*)mp;
        mp1(test,sel);
        
        mp = [ATest methodForSelector:sel];
        void(*mp2)(id,SEL) = (void*)mp;
        mp2(test,sel);
        
        mp = [ATest instanceMethodForSelector:sel];
        void(*mp3)(id,SEL) = (void*)mp;
        mp3(test,sel);
        
        
    }
    return 0;
}

运行结果如下:

2018-09-11 20:36:54.962026+0800 Test1[73782:1635537] Hello, World!

2018-09-11 20:36:54.962480+0800 Test1[73782:1635537] instance say hi={

};

2018-09-11 20:36:54.962941+0800 Test1[73782:1635537] class say hi

2018-09-11 20:36:54.963015+0800 Test1[73782:1635537] instance say hi={

};

转载于:https://www.cnblogs.com/yongbufangqi1988/p/9630157.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值