• 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"];

    }

  • 相关阅读:
    ant-design-vue——子组件通过$parent修改父组件的值时无效问题及解决方法
    vue——quill-editor自定义图片上传
    ES6——var、let、const三者的区别
    js——数组/对象常用方法总结
    28.最长回文子序列
    27.马拉车
    26.扫雷一次点击
    JS添加内容之方法里传AJAX参数
    JQ 实现加载其他页面的H5代码 JQ加载H5独立导航栏代码
    CentOS 7不能上网 解决方法
  • 原文地址:https://www.cnblogs.com/edensyd/p/8716962.html
Copyright © 2020-2023  润新知