美文网首页
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基本使用

    OC为动态语言原因是其具有独特的消息传递机制其运行时runtime可以很好的体现出来OC代码的消息调用都能通...

  • iOS之Runtime(二)

    一:@@@《基础篇》@@@ 二:@@@《应用篇》@@@ 本篇将会结合Rutime其动态特性,总结Rutime的具体...

  • Runtime学习

    rutime基本概念 runtime是什么 runtime是属于OC的底层,是一套比较底层的纯C语言API, 属于...

  • 初识Rutime

    一、runtime简介 RunTime简称运行时。OC就是运行时机制,也就是在运行时候的一些机制,其中最主要的是消...

  • IOS Rutime学习

    1.什么是Runtime Runtime是Object-C中的一个库,主要用C和汇编写的,OC编写的代码最终都会转...

  • Runtime 知识点

    Runtime 是什么? Runtime 有什么作用? 1. Rutime 是什么? 1.1. Runtime 简...

  • rutime动态添加方法

    import "ViewController.h" import "Person.h" @interface Vi...

  • iOS rutime(1)-isa详解

    1. OC的定义 Objective-C是一门动态性比较强的编程语言,跟C和C++等语言有着很大的不同.Objec...

  • iOS rutime(1)-isa详解

    OC的定义Objective-C是一门动态性比较强的编程语言,跟C和C++等语言有着很大的不同.Objective...

  • chan(rutime. hchan)结构

    chan实际结构是runtime.hchan(https://github.com/golang/go/blob/...

网友评论

      本文标题:Rutime基本使用

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