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;
}

運行結果以下:app

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

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

};spa

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

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

};blog

相關文章
相關標籤/搜索