class_addMethod 简介

本文详细介绍了如何使用Objective-C运行时API中的class_addMethod函数来为类动态添加方法及其具体实现。文中提供了两种不同的实现示例,一种是使用C语言风格的函数,另一种则是使用Objective-C的方法实现。
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 含义

CodeMeaning
cA char
iAn int
sA short
lA long
qA long long
CAn unsigned char
I(大写i)An unsigned int
SAn unsigned short
LAn unsigned Long
QAn unsigned long long
fA float
dA double
BA C++ bool or C99 _Bool
vA 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
(name=type...)A union
bnumA bit field of num bits
^typeA pointer to type
?An unknown type (among other things, this code is used for function pointers)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值