ios runtime专题

Runtime | 动态添加方法

2019-08-04  本文已影响0人  字符管理师

准备工作

#import <objc/runtime.h>
@property (nonatomic, strong) Persion* persion;

代码演示

/// 3.使用runtime来动态添加方法
- (void) rylsj_AddMethod {
    class_addMethod([self.persion class], @selector(run:), (IMP)runMethod, "v@:@");
    
}

方法实现

void runMethod(id self, SEL _cmd, NSString* rylsj) {
    NSLog(@"%@", rylsj);
}

说明

"v@:@": v表示void, @表示id, :表示 SEL
runMethod 里面会有两个默认的参数,self和_cmd

方法调用

 if ([self.persion respondsToSelector:@selector(run:)]) {
        [self.persion performSelector:@selector(run:) withObject:@"66 rylsj"];
    } else {
        NSLog(@"方法没有实现!!");
    }
上一篇 下一篇

猜你喜欢

热点阅读