objective-c中关于类型编码的解释

本文介绍如何使用class_addMethod函数在Objective-C中为类动态添加方法。解释了该函数的参数含义及其使用方法,并提供了如何定义方法签名和类型编码的指导。

在某些情况下,我们需要动态的向一个类插入一个实例方法(也可以是一个类方法);这时我们可以用class_addMethod函数来完成:

 BOOL class_addMethod ( Class cls, SEL name, IMP imp, const char *types ); 

在Objective-C Runtime Reference 中可以看到各个参数的含义:

Parameters
**cls**     
The class to which to add a method.

**name**    
A selector that specifies the name of the method being added.

**imp**     
A function which is the implementation of the new method. The function must take at least two arguments—self and _cmd.

**types**   
An array of characters that describe the types of the arguments to the method. For possible values, see Objective-C Runtime Programming Guide > Type Encodings. Since the function must take at least two arguments—self and _cmd, the second and third characters must be “@:” (the first character is the return type).

前面几个参数比较好理解,我们来看看最后一个:这是一个字符串按照imp的签名依次排列返回值和各个参数。apple开发者官网有对应的编码:
Type Encodings

我们也可以用@encode来查看实际的编码,比如:

NSLog(@"%s",@encode(int *));
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值