前言
- 1, 上一章简单讲述了runtime动态添加方法,但是都是没有参数的方法,下面我们学习一下带参数的方法.
runtime动态添加方法的补充
在ViewController.m文件中
#import "ViewController.h"
#import "WGStudent.h"
#import <objc/message.h>
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
WGStudent *student = [[WGStudent alloc] init];
[student performSelector:@selector(study:) withObject:@"在简书上学习iOS"];
}
@end
在WGStudent.m文件中
#import "WGStudent.h"
#import <objc/message.h>
@implementation WGStudent
// 返回值Void-> V id -> @ SEL -> : NSString -> @
// v@:@
void study(id self, SEL _cmd, NSString *jianshu)
{
NSLog(@"Alex%@",jianshu);
}
+ (BOOL)resolveInstanceMethod:(SEL)sel
{
if (sel == NSSelectorFromString(@"study:")) {
class_addMethod(self, sel, (IMP)study, "v@:@");
return YES;
}
return [super resolveInstanceMethod:sel];
}
@end
- 注意 : type是如何书写的(直接去查阅官方文档)