zoukankan      html  css  js  c++  java
  • Runtime(运行时)003-动态添加方法

    class_addMethod

    #import "Person.h"

    #import <objc/message.h>

    @implementation Person

    /*

     OC的方法调用,会传递两个隐式参数!给IMP(方法实现)!!

     objc_msgSend(self,_cmd);

     id self 方法调用者

     SEL _cmd 方法编号

     */

    //instanceMethod 实例方法  classMethod 类方法

    //如果该类接收到一个没有实现的实例方法,就会来到这里

    +(BOOL)resolveInstanceMethod:(SEL)sel {

        //NSLog(@"%@",NSStringFromSelector(sel));

        //动态添加一个方法!!

        /*

         1.class 哪个类

         2.SEL

         3.IMP 函数的指针

         4.返回值类型

         */

        class_addMethod(self, sel, (IMP)haha, "v@:@");

        return [super resolveInstanceMethod:sel];

    }

    void haha(id obj, SEL sel , NSString*objc) {

        //NSLog(@"吃到了%@",objc);

        //obj 调用者

        //sel 方法编号

        //objc 参数

        NSLog(@"%@--%@--%@",obj,NSStringFromSelector(sel),objc);//(null)--eat:--汉堡!!

        //objc_msgSend(p,@selector(eat:),@"汉堡");

    }

    void myMethodIMP(id self, SEL _cmd)//默认参数

    {

        // implementation ....

    }

  • 相关阅读:
    题解 CF1304E 【1-Trees and Queries】
    题解 P4302 【[SCOI2003]字符串折叠】
    题解 P2070 【刷墙】
    题解 P1278 【单词游戏】
    题解 P1985 【[USACO07OPEN]翻转棋】
    题解 P2642 【双子序列最大和】
    Python面向对象之反射
    Python面向对象之进阶
    Python面向对象之多态、封装
    Python面向对象之继承
  • 原文地址:https://www.cnblogs.com/StevenHuSir/p/Runtime_AddMethod.html
Copyright © 2011-2022 走看看