先介绍下class_addMethod这个fangfa

  1.  
    /**
  2.  
    * Adds a new method to a class with a given name and implementation.
  3.  
    *
  4.  
    * @param cls The class to which to add a method.
  5.  
    * @param name A selector that specifies the name of the method being added.
  6.  
    * @param imp A function which is the implementation of the new method. The function must take at least two arguments—self and _cmd.
  7.  
    * @param types An array of characters that describe the types of the arguments to the method.
  8.  
    *
  9.  
    * @return YES if the method was added successfully, otherwise NO
  10.  
    * (for example, the class already contains a method implementation with that name).
  11.  
    *
  12.  
    * @note class_addMethod will add an override of a superclass's implementation,
  13.  
    * but will not replace an existing implementation in this class.
  14.  
    * To change an existing implementation, use method_setImplementation.
  15.  
    */
  16.  
    OBJC_EXPORT BOOL class_addMethod(Class cls, SEL name, IMP imp,
  17.  
    const char *types)
  18.  
    OBJC_AVAILABLE(10.5, 2.0, 9.0, 1.0);

这是文档

描述就是:给一个类添加一个新的方法和该方法的具体实现

参数:

第一个

Class cls

cls :你要添加新方法的那个类

第二个

SEL name

name :要添加的方法

第三个

IMP imp

imp:指向实现方法的指针   就是要添加的方法的实现部分

第四个

const char *types

*types:我们要添加的方法的返回值和参数   叫 type encodings 这个东西怎么写我就不说了 可以去查  在这里我有一个懒办法得到它不用暴力手打   往后看

然后这个方法的描述和参数说完了,下面说说他用在哪,

给一个类用运行时添加一个方法   他可以用来解决我们开发中的这个问题------“unrecognized selector sent to instance 0x7faa2a132c0”

在OC中我们调用一个方法时 有个关键字 叫  “消息机制”    就是执行  [receiver message]; 这句代码其实就是发送了一个消息 (发消息的详细过程我就不写了 感兴趣 去查),

消息里面带着你调用这个方法的名称和参数以及是哪个对象发送的消息,然后 发出消息后  如果有对应的方法响应,就执行方法,没有的话就报“unrecognized selector sent to instance 0x7faa2a132c0” ,然后就crash   ,为了防止crash我们可以用class_addMethod给找不到对应方法即将crash的消息添加一个与之对应的方法来防止其因为找不到相应方法而crash

在OC中找不到对相应的实现方法时  有补救机制 即 会先调用动态决议方法   该方法解决不了问题 再调用重定向方法    都解决不了问题是 crash

动态决议方法:

  1.  
    + (BOOL)resolveClassMethod:(SEL)sel OBJC_AVAILABLE(10.5, 2.0, 9.0, 1.0);
  2.  
    + (BOOL)resolveInstanceMethod:(SEL)sel OBJC_AVAILABLE(10.5, 2.0, 9.0, 1.0);

重定向方法:

- (id)forwardingTargetForSelector:(SEL)aSelector OBJC_AVAILABLE(10.5, 2.0, 9.0, 1.0);

下面上代码:给一个类的对象调用一个未实现的方法  然后用runtime 在动态决议方法中为其添加实现  防止crash

Person类

  1.  
    #import "Person.h"
  2.  
    #import <objc/runtime.h>
  3.  
     
  4.  
    @implementation Person
  5.  
     
  6.  
     
  7.  
    + (BOOL)resolveInstanceMethod:(SEL)sel {
  8.  
    Method exchangeM = class_getInstanceMethod([self class], @selector(eatWithPersonName:));
  9.  
    class_addMethod([self class], sel, class_getMethodImplementation(self, @selector(eatWithPersonName:)),method_getTypeEncoding(exchangeM));
  10.  
    return YES;
  11.  
    }
  12.  
     
  13.  
    - (void)eatWithPersonName:(NSString *)name {
  14.  
    NSLog(@"Person %@ start eat ",name);
  15.  
    }
  16.  
     
  17.  
     
  18.  
     
  19.  
    @end

里面重写resolveInstanceMethod方法  给找不到实现的方法 添加实现  - (void)eatWithPersonName:(NSString *)name;

第一句

Method exchangeM = class_getInstanceMethod([self class], @selector(eatWithPersonName:));

是为下面method_getTypeEncoding(exchangeM) 做铺垫  这样就拿到了eatWithPersonName方法的type encodings 用作class_addMethod的第四个参数,就是上面我提到的不用暴力手打的获取type encodings的方法

然后调用 class_addMethod  为当前类[self class] 的sel 方法 添加实现 class_getMethodImplementation(self, @selector(eatWithPersonName:)) 这一串就是拿到方法eatWithPersonName的IMP指针  然后最后一个参数是  type encodings

然后测试

  1.  
    Person *person = [[Person alloc]init];
  2.  
    //调用Person未实现方法eat
  3.  
    [person performSelector:@selector(eat) withObject:@"minzhe"];

运行结果:

2017-07-14 14:41:35.297 RunTimeAddMethod[1458:379458] Person minzhe start eat 

好了   添加上了    这样就没有 crash

iOS用runtime给一个类动态添加方法 ---class_addMethod的更多相关文章

  1. ios开发runtime学习三:动态添加方法(实际应用少,面试)

    #import "ViewController.h" #import "Person.h" /* 1: Runtime(动态添加方法):OC都是懒加载机制,只要 ...

  2. 使用runtime给类动态添加方法并调用 - class_addMethod

    上手开发 iOS 一段时间后,我发现并不能只着眼于完成需求,利用闲暇之余多研究其他的开发技巧,才能在有限时间内提升自己水平.当然,“其他开发技巧”这个命题对于任何一个开发领域都感觉不找边际,而对于我来 ...

  3. ios开发runtime学习四:动态添加属性

    #import "ViewController.h" #import "Person.h" #import "NSObject+Property.h& ...

  4. 给python类动态添加方法(method)

    群里有人问如何做到 def foo(): pass class Bar(object): pass Bar.set_instance_method(foo) b = Bar() b.foo() 这个其 ...

  5. ios的runtime为什么可以动态添加方法

    一句话概括 每个instance都有一个isa,这个isa,里面含有所有的方法列表,ios提供库函数增加,修改,即实现了动态添加方法

  6. 使用TypeDescriptor给类动态添加Attribute

    给类动态添加Attribute一直是我想要解决的问题,从msdn里找了很久,到Stack Overflow看了不少文章,算是最终有了答案. 先是有这样的一段解释 Attributes are stat ...

  7. iOS运行时使用(动态添加方法)

    1 举例  我们实现一个Person类 然后Person 其实是没得对象方法eat:的 下面调用person的eat方法 程序是会奔溃的 那么需要借助运行时动态的添加方法 Person *p = [[ ...

  8. python装饰器、继承、元类、mixin,四种給类动态添加类属性和方法的方式(一)

    介绍装饰器.继承.元类.mixin,四种給类动态添加类属性和方法的方式 有时候需要給类添加额外的东西,有些东西很频繁,每个类都需要,如果不想反复的复制粘贴到每个类,可以动态添加. # coding=u ...

  9. 快速上手Runtime(四)之动态添加方法

    如果一个类方法非常多,加载类到内存的时候也比较耗费资源,可以使用动态给某个类,添加方法解决.做到优化内存,节省资源的效果. // // Person.m // ResolveInstanceMetho ...

  10. php里面用魔术方法和匿名函数闭包函数动态的给类里面添加方法

    1.认识  __set  (在给不可访问属性赋值时,__set() 会被调用) 也就是说你再访问一个类里面没有的属性,会出发这个方法 class A{ private $aa = '11'; publ ...

随机推荐

  1. [localhost-startStop-1]

    第一次遇到Tomcat在Linux服务器启动卡住的情况,情况很简单,tomcat启动以后卡在INFO: Deploying web application directory ......这句话,具体 ...

  2. 19.内容提供者ContentProvider

    之前我们学习了Android数据持久化的技术,包括文件存储(内部存储).SharedPreferences存储以及数据库存储. 这些持久化技术所保存的数据基本都是在当前应用程序中访问. Android ...

  3. (未完成)JAVAWEB学习——

    一.Servlet开发 1.sun公司提供的一种动态web资源开发技术,本质上就要是一段Java小程序,可以将Servlet加入到容器中运行Servlet. *servlet容器 -- 能够运行ser ...

  4. django 关联类 DoesNotExist: User matching query does not exist.

    问题就是 关联类为空找不到 在或者geattr / hasattr / obj. item 会抛出异常 无法通过判断处理 捕获异常 try: tmp_data['demand_dept_name'] ...

  5. LeNet,AlexNet,VGG,GoogLeNet

    卷积神经网络-LeNet 理解channel:卷积操作完成后输出的 out_channels ,取决于卷积核的数量.此时的 out_channels 也会作为下一次卷积时的卷积核的 in_channe ...

  6. nginx日志按日期存储

    http {     include       mime.types;     default_type  application/octet-stream;     map $time_iso86 ...

  7. office2016word打开总是提示安全模式

    突然打开word和Excel提示是否使用安全模式,如果选择否就自动退出office,选择是进入后,编辑一下也会自己退出,非常郁闷. 之后上网查看,尝试了许多: 1.win+R 运行%appdata%\ ...

  8. Jenkins自动化部署(linux环境)---构建任务

    用jenkins创建一个构建任务 1.这里我代码仓库用的是码云(github也是一样的)输入仓库地址.因为仓库是私有的所以会有报错提示 这里要添加Credentials.就是你码云或者github账号 ...

  9. 初始化centos环境脚本

    #! /bin/bashecho "java环境初始化开始"#功能描述: Centos8.5系统自动初始化脚本#自动配置:IP地址\Yum源\docer\docker-compos ...

  10. linux 安装 talib 的完美姿势!

    安装 TA-Lib $ wget http://prdownloads.sourceforge.net/ta-lib/ta-lib-0.4.0-src.tar.gz $ tar -zxvf ta-li ...