美文网首页
Rutime基本使用

Rutime基本使用

作者: coderHe | 来源:发表于2017-05-19 11:57 被阅读0次

          OC为动态语言原因是其具有独特的消息传递机制其运行时runtime可以很好的体现出来OC代码的消息调用都能通过runtime调用.比如在oc中一个对象调用一个方法[obj  method]通过这种形式去调用的,转换到runtime中就是通过msg_send();方法去调用.之所以说oc是一门动态语言是因为你可以随时去更改一个类中的方法,为一个类添加方法等等。而且在一些面试题目中会问到分类中是否可以添加属性。一般情况下直接添加属性是不行的。但是如果市容runtime的话就可以完成属性的添加。不多说直接上代码教你如何使用rutime

    1.runtime常用方法介绍

    //获取类

    Class PersonClass = object_getClass([Person class]);

    SEL是selector在Objc中的表示:

    SEL oriSEL = @selector(test1);

    //获取类方法

    Method oriMethod = Method class_getClassMethod(Class cls , SEL name);

    //获取实例方法

    Method class_getInstanceMethod(Class cls , SEL name)

    //添加方法

    BOOL addSucc = class_addMethod(xiaomingClass, oriSEL, method_getImplementation(cusMethod), method_getTypeEncoding(cusMethod));

    //替换原有方法

    class_replaceMethod(toolClass, cusSEL, method_getImplementation(oriMethod), method_getTypeEncoding(oriMethod));

    //交换2个方法

    method_exchangeImplementations(oriMethod, cusMethod);

    //获取属性列表

    objc_property_t *propertyList = class_copyPropertyList([self class], &count);

    //获取方法列表

    Method *methodList = class_copyMethodList([self class], &count);

    //获取成员变量列表

    Ivar *ivarList = class_copyIvarList([self class], &count);

    /参数policy:存储策略(assign、copy、retain就是strong)

    void objc_setAssociatedObject(id object , const void *key ,id value ,objc_AssociationPolicy policy)

    //利用参数key将对象object中存储的对应值取出来:

    id objc_getAssociatedObject(id object , const void *key)

    这2个方法可以为分类添加属性

    上面的方法基本上对runtime的使用没有多大问题了

    2.runtime的使用

    @interface ChatModel (AddPro)

    @property(nonatomic,copy)NSString*names;

    @property(nonatomic,strong)RunTimeModel*runtimemodel;

    为chatmodel的分类添加2个属性用到runtime中的关联属性

    而且runtime可以使用到dic转model中去像现在使用的YYModel等转模型的工具都使用了遍历model中成员变量的方法。如果一个模型属性过多的时候可通过遍历成员变量去实现归档解档的工作。

    替换原有方法:

    用当前runnn方法替换runtimemodel中的say方法

    使用runtime为runtimemodel添加addmethods方法

    其他的使用可以件demo:github地址:github.com/stevehe-campray/runtime

    相关文章

      网友评论

          本文标题:Rutime基本使用

          本文链接:https://www.haomeiwen.com/subject/rwqsxxtx.html