• IOS高级开发~Runtime(一)


    #import <Foundation/Foundation.h>
    
    @interface CustomClass : NSObject
    
    -(void)fun1;
    
    @end
    
    @interface CustomOtherClass : NSObject
    
    -(void)fun2;
    
    @end
    #import "TestClass.h"
    #import <objc/runtime.h>
    @implementation TestClass
    
    + (BOOL)resolveInstanceMethod:(SEL)sel {
        Method exchangeM = class_getInstanceMethod([self class], @selector(eatWithPersonName:));
        //拿到IMP指针
        class_addMethod([self class], sel, class_getMethodImplementation(self, @selector(eatWithPersonName:)),method_getTypeEncoding(exchangeM));
        return YES;
    }
    - (void)eatWithPersonName:(NSString *)name {
        NSLog(@"Person %@ start eat ",name);
    }
    @end

    /**

     对象拷贝

     */

    -(void)copyObj{

        CustomClass *obj = [CustomClass new];

        NSLog(@"对象拷贝:%p",&obj);

        //完全是一个新的对象

        id objTest = object_copy(obj,sizeof(obj));

        NSLog(@"%p", &objTest);

        [objTest fun1];

    }

    /**

     对象释放

     */

    -(void)objectDispose{

        CustomClass *obj = [CustomClass new];

        (void)(NSLog(@"---%ld",obj.retainCount)),

        object_dispose(obj);

        //(void)(NSLog(@"---%ld",obj.retainCount)),

        //[obj release];

        //NSLog(@"---%ld",obj.retainCount);

        //[obj fun1];

    }

    /**

     更改对象的类

     */

    -(void)setClassTest{

        CustomClass *obj = [CustomClass new];

        [obj fun1];

        

        Class aclass = object_setClass(obj, [CustomOtherClass class]);

        //obj 对象的类被更改了    swap the isa to an isa

        NSLog(@"aClass:%@",NSStringFromClass(aclass));

        NSLog(@"obj class:%@",NSStringFromClass([obj class]));

        [obj fun2];

    }

    -(void)getClassTest{

        CustomClass *obj = [CustomClass new];

        Class alogClass = object_getClass(obj);

        NSLog(@"--get:%@",NSStringFromClass(alogClass));

    }

    /**

     获取对象的类名

     */

    - (void) getClassName{

        

        CustomClass *obj = [CustomClass new];

        NSString *className = [NSString stringWithCString:object_getClassName(obj) encoding:NSUTF8StringEncoding];

        NSLog(@"className:%@",className);

    }

    /**

     动态给一个类添加方法

     */

    - (void)oneParam{

        TestClass *instance = [[TestClass alloc]init];

        //方法添加

        [instance performSelector:@selector(eatWithPersonName:) withObject:@"mujin"];

    }

  • 相关阅读:
    商城问题
    web基础重难点
    业务流程
    主流框架面试题
    数据库:索引-引擎-优化
    【jquey代码】基于选中的checkbox 删除对应的一行数据
    javascript中获取json对象的value,拼接到页面上
    【json对象和json格式的字符串】
    【idea中创建springMVC项目的2个坑】不识别@Autowired 以及 Mapper.xml的配置
    【eclipse和idea】创建spring项目时的一处不同
  • 原文地址:https://www.cnblogs.com/edensyd/p/8716962.html
Copyright © 2020-2023  润新知