美文网首页
runtime 中 class_addMethod 简介

runtime 中 class_addMethod 简介

作者: 学无止境666 | 来源:发表于2020-04-04 10:13 被阅读0次
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)

原文地址

相关文章

  • runtime 中 class_addMethod 简介

    在runtime.h中定义, 其作用是给一个类添加新的方法及该方法的具体实现.其 返回值为 BOOL 类型, ye...

  • class_addMethod

    runtime版本objc4-723 class_addMethod申明于 runtime.h: 实现于objc-...

  • Runtime 方法交换

    Runtime基础使用场景-拦截替换方法(class_addMethod ,class_replaceMethod...

  • class_addMethod和class_replaceMet

    runtime中方法交换的经典代码如下,其中的class_addMethod和class_replaceMetho...

  • runtime

    让你快速上手Runtime说说objcRuntime的一些妙用(class_addMethod,class_rep...

  • runTime class_addMethod

    class_addMethod(Class cls, SEL name, IMP imp, const char ...

  • iOS strong & copy @synthes

    iOS Runtime 简单使用[/p/be132b3d86bf] class_addMethod第四个参数含义官...

  • 实用技术-1

    PPT 笔记 const,static,extern简介 RunTime 一、runtime简介 RunTime简...

  • iOS-Runtime

    RunTime简介1.runtime是 OC 的底层实现, runtime API 都是纯 c 代码.2.所有类中...

  • class_addMethod实解

    闲来无事,整理了一下runtime的知识,发现方法交换里面有个不明白的点:class_addMethod 这个方法...

网友评论

      本文标题:runtime 中 class_addMethod 简介

      本文链接:https://www.haomeiwen.com/subject/yujdphtx.html