zoukankan      html  css  js  c++  java
  • iOS运行时使用(动态添加方法)

    1 举例  我们实现一个Person类 然后Person 其实是没得对象方法eat:的

    下面调用person的eat方法 程序是会奔溃的 那么需要借助运行时动态的添加方法

    Person *p = [[Person alloc]init];
        [p performSelector:@selector(eat:) withObject:@"鸡腿"];

    在perosn.m文件中进行实现运行时动态添加方法

    //
    //  Person.m
    //  运行时(动态添加方法)
    //
    //  Created by ALD on 2018/6/4.
    //  Copyright © 2018年 ALD. All rights reserved.
    //
    
    #import "Person.h"
    #import <objc/message.h>
    @implementation Person
    //使用到了未定义的类方法
    //+(BOOL)resolveClassMethod:(SEL)sel{
    //
    //}
    
    // 定义eat 方法 默认会前面两个隐式参数 id self, SEL _cmd  第三个才是我们自己传入的参数
    void eat(id self, SEL _cmd ,id object ){
        NSLog(@"吃了%@", object);
    }
    //使用到了未定义的对象方法
    +(BOOL)resolveInstanceMethod:(SEL)sel{
        NSLog(@"%@", NSStringFromSelector(sel));
        if (sel  == @selector(eat:)) {
            //动态添加方法
            
            /**
             <#Description#>
    
             @param cls#> 那个类 description#>
             @param name#> 方法名 description#>
             @param imp#> 方法指针 description#>
             @param types#> 方法类型 description#>
             @return <#return value description#>
             */
    //        class_addMethod(<#Class  _Nullable __unsafe_unretained cls#>, <#SEL  _Nonnull name#>, <#IMP  _Nonnull imp#>, <#const char * _Nullable types#>)
            class_addMethod([self class], @selector(eat:), (IMP)eat, "v");
        }
        return [super resolveInstanceMethod:sel];
        
    }
    @end

    对 class_addMethod  不太理解里面参数含义可以去文档查询 拷贝 shift + command + 0 然后搜索你想查的方法

  • 相关阅读:
    FTP协议操作
    [转贴]SQL2005数据类型
    传智博客学习0512
    20120515传智学习
    20120516分析三层中的null的处理
    20120520晚
    你懂不懂我不知道,反正我是晕了
    20120509小记
    javascript 循环语句 while、dowhile、forin、for用法区别
    C#的一些学习方法
  • 原文地址:https://www.cnblogs.com/ZhangShengjie/p/9136642.html
Copyright © 2011-2022 走看看