Runtime | 动态添加方法

准备工作

  • 添加头文件并声明一个Person类并设置属性

#import 
@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(@"方法没有实现!!");
    }

你可能感兴趣的:(Runtime | 动态添加方法)