runtime使用之消息发送的本质

2016-03-08  本文已影响160人  Alexander

前言

一, runtime简介

二, runtime的作用

1, 发送消息

三, runtime的使用场景

 // 新建一个学生类WGStudent, 在类中什么一个对象方法和类方法.
 #import <Foundation/Foundation.h>

WGStudent.h文件
@interface WGStudent : NSObject

  // - (void)study;
  // + (void)eat;

@end

WGStudent.m文件
#import "WGStudent.h"

@implementation WGStudent

- (void)study {
    NSLog(@"学习数学");
}

+ (void)eat {
    NSLog(@"吃饭");
}
@end
#import "ViewController.h"
#import "WGStudent.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];

//  对象发送消息
    // OC中调用对象方法
    WGStudent *student = [[WGStudent alloc] init];

    [student study];

    // [student study]的本质就是让对象发送消息
    objc_msgSend(student @selecter(study));

// 类调用对象方法,发送消息
// 调用类方法的方式:两种

    // 第一种通过类名调用
    [student eat];
    // 第二种通过类对象调用
    [[student class] eat];

    // 用类名调用类方法,底层会自动把类名转换成类对象调用
    // 本质:让类对象发送消息
    objc_msgSend([student class], @selector(eat));
}

@end

四, 解析创建一个对象时,如何使用runtime转化OC的.

// 解析创建对象过程
WGStudent *student = [[WGStudent alloc] init];

// 1, 分配存储空间
    WGStudent *student = [WGStudent alloc];
--> 使用runtime创建对象
    objc_msgSend([WGStudent class], @selector(alloc));

// 2, 初始化
    student = [student init];
--> 使用runtime进行初始化
    student = objc_msgSend(student, @selector(init));

// 3, 调用对象方法
    [student study];
--> 使用runtime调用方法
    objc_msgSend(student, @selector(study));


    ((NSObject * (*)(id, SEL))objc_msgSend)(self,@selector(eat));
    objc_msgSend(self,@selector(eat));

上一篇 下一篇

猜你喜欢

热点阅读