BOOL class_addMethod(Class _Nullable cls, SEL _Nonnull name, IMP _Nonnull imp, const char * _Nullable types)
在runtime.h中定义, 其作用是给一个类添加新的方法及该方法的具体实现.
其 返回值为 BOOL 类型, yes表示添加方法成功, no表示添加方法失败.
参数介绍
* Adds a new method to a class with a given name and implementation.
* @param cls 将要添加方法的类, 可以传 [类名 class]
* @param name 将要添加的方法名, 传的类型为 @selector(方法名).
* @param imp 实现这个方法的函数, 传的类型 (1) C语言写法: (IMP) 方法名; (2) OC写法: class_getMethodImplementation(self, @selector(方法名))
* @param types 添加方法的返回值和参数数组
举例说明下
1. C语言实现
void exchange_function(id self, SEL _cmd, NSString *str){
NSLog(@"exchange_function");
}
@implementation myClass : NSObject
- (void)exchangeMethodWithSel:(SEL)sel{
class_addMethod([self class], sel, (IMP)exchange_function, "v@:@");
}
@end
------------------------------------------------------------------------------------
2. OC实现
@implementation myClass : NSObject
- (void)exchange_functionTwo:(NSString *)str{
NSLog(@"exchange_functionTwo");
}
- (void)exchangeMethodWithSel:(SEL)sel{
// "v@:@":v表示是添加方法无返回值, @表示是id(也就是要添加的类); :表示添加的方法类型 @表示:参数类型
class_addMethod([self class], sel, class_getMethodImplementation([self class], @selector(exchange_functionTwo:)), "v@:@");
@end
const char *type 含义
code | Meaning |
---|---|
c | A char |
i | An int |
s | A short |
l | A long |
q | A long long |
C | An unsigned char |
I(大写i) | An unsigned int |
S | An unsigned short |
L | An unsigned Long |
Q | An unsigned long long |
f | A float |
d | A double |
B | A C++ bool or C99 _Bool |
v | A void |
* | A character string (char *) |
@ | An object (whether statically typed or typed id) |
# | A class object (Class) |
: | A method selector (SEL) |
[array type] | An array |
{name=type...} | A structure |
bnum | A bit field of num bits |
^type | A pointer to type |
? | An unknown type (among other things, this code is used for function pointers) |
网友评论