简单理解runtime

  1. runtime是一套底层的C语言API,包含很多强大实用的C语言数据类型、C语言函数
  2. 平时我们编写的代码,底层都是基于runtime实现的
runtime可以达到什么目的?
  • 能动态产生、修改、删除一个类、成员变量、方法
runtime可以用在哪些地方

类别添加属性
Jason转Model
Method Swizzling
hack

具体使用如下:
自定义一个类mySelvesLife

#import 

@interface mySelvesLife : NSObject

@property (nonatomic, assign) NSInteger age;
@property (nonatomic, copy  ) NSString  *name;
@property (nonatomic, assign) float     height;

- (void)eat;

- (void)drink;

@end

自定义类的实现部分

#import "mySelvesLife.h"

#import 

@implementation mySelvesLife

+(void)load {
//获取一个类的指定成员方法
    Method eatMethod = class_getInstanceMethod(self, @selector(eat));
    Method drinkMethod = class_getInstanceMethod(self, @selector(drink));
//交换两个方法的实现
    method_exchangeImplementations(eatMethod, drinkMethod);
}

- (void)eat {
    NSLog(@"eat");
}

- (void)drink {
    NSLog(@"drink");
}

@end

runtime的具体使用

#import "ViewController.h"

//成员变量、类、方法
#import 

#import "mySelvesLife.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
//    [self ivars];
    
//    [self methods];
    
    [self exchangeMethod];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)ivars {
    unsigned int count = 0;
    //获取一个类的所有成员属性
    Ivar *ivars = class_copyIvarList([mySelvesLife class], &count);
    for (int i = 0; i < count; i++) {
        Ivar ivar = ivars[i];
        //获取属性名
        const char *name = ivar_getName(ivar);
        //获取属性类型
        const char *class = ivar_getTypeEncoding(ivar);
        NSLog(@"ivarName:%s,ivarType:%s",name,class);
    }
    
    //释放ivars:C语言在ARC中通过copy产生,需要手动释放
    free(ivars);
}

- (void)methods {
    unsigned int count = 0;
    //获取一个类的所有方法
    Method *methods = class_copyMethodList([mySelvesLife class], &count);
    for (int i = 0; i < count; i++) {
        Method method = methods[i];
        SEL sel = method_getName(method);
        NSLog(@"sel:%@",NSStringFromSelector(sel));
    }
    
    free(methods);
}

- (void)exchangeMethod {
    mySelvesLife *myself = [[mySelvesLife alloc] init];
    [myself eat];
}

@end

#import 中有很多C语言函数,我们可以慢慢探索,另外还有一个类#import 是消息机制,有兴趣可以看看。
其中,

打印出来的.cxx_destruct方法作用是ARC下对象的成员变量在编译器的. cxx_destruct方法自动释放,具体内容看这里

+load是在应用启动的时候就会调用,而initialize是在实例化该类的时候才会调用。交换方法不是必须写在这里。

initialize方法和init区别

在程序运行过程中,他会在程序中每个类调用一次initialize。这个调用的时间发生在你的类接收到消息之前,但是在它的父类接收到initialize之后。具体看这里

你可能感兴趣的:(简单理解runtime)