Runtime基础应用

来源:互联网 发布:spss17.0软件下载 编辑:程序博客网 时间:2024/05/19 22:46

一. Runtime概述。

1.Runtime是一套由C语言API组合的Runtime库。

2.Runtime会尽可能把代码的执行决策推迟到运行时。

3.OC是动态语言,OC代码最终都会转换成底层Runtime的代码。

例:

//oc的函数调用        [personPtr setAge:10];        NSLog(@"%ld",(long)personPtr.age);                ///c函数调用        objc_msgSend(personPtr, @selector(setAge:),20);        NSLog(@"%ld",(long)personPtr.age);

二. Runtime的使用

1.动态获取/创建类。

2.动态为一个类增加属性和方法。

3.在程序运行时遍历类中的实例变量,属性或方法。

4.调换两个方法的逻辑实现(Method Swizzle)。


三.Runtime简单入手学习。

三(1).在使用Runtime之前 ,要引入系统头文件。

#import <objc/runtime.h> 

三(2).创建一个类,继承于NSObject  然后在类里面声明两个属性一个方法。

#import <Foundation/Foundation.h>@interface Person : NSObject@property (nonatomic,copy) NSString *name;@property (nonatomic,assign) NSInteger age;+(instancetype)person;@end

1.  动态获取类型。(在main实现 如下代码

  ///动态获取对象类型        Person *personPtr = [[Person alloc]init];        // [personPtr class] 获取动态类型        NSLog(@"%@",[personPtr class]);                //创建Class对象 (动态获取变量,属性,对象 会使用)        Class classPtr = personPtr.class;        unsigned int outCount = 0;

打印出来的就是类的类型了。


2。动态获取类中的实例变量。(在main实现 如下代码)

 //动态获取类中的实例变量        Ivar *ivarptr =  class_copyIvarList(classPtr, &outCount);        for (int i = 0; i<outCount; i++)        {            Ivar *ivar = &ivarptr[i];            NSLog(@"实例变量:%s",ivar_getName(*ivar));        }

3. 动态遍历类中的属性。(在main实现 如下代码)

///动态遍历类中的属性         objc_property_t *objcproperty =  class_copyPropertyList(classPtr, &outCount);          for (int i = 0; i<outCount; i++)          {              objc_property_t perperty = objcproperty[i];              NSLog(@"属性:%s",property_getName(perperty));          }

4. 动态遍历类中的对象 。(在main实现 如下代码)

///动态遍历对象       Method *method = class_copyMethodList(classPtr, &outCount);        for (int i = 0; i<outCount; i++)        {            Method meth = method[i];            SEL selector = method_getName(meth);            NSLog(@"%@",NSStringFromSelector(selector));        }

总结:Ivar、objc_property、Method 这些都系统提供的函数。会用就行。像button的定义一样。


0 0