完善自我/CodingObjective-C Runtime计算机技术一锅炖

Objective-C的runtime机制00-概述

2016-01-21  本文已影响722人  qiushuitian

运行时是OC的一个大特性。iOS的Runtime,使得很多本来在编译阶段的事情,放在了运行阶段确定。这是OC作为动态语言的华彩部分.

体验一下什么是动态语言

对于静态语言,比如下面一段C语言,testEntry函数中调用functionA,就执行functionA定义的代码,调用functionB,就执行functionB定义的代码。编译链接完成之后,执行逻辑和顺序就固定了。

#include < stdio.h >  
void testEntry()  
{  
    functionA(); // 输出 I am functionA!
    functionB();  // 输出 I am functionB!
}   
void functionA()
{
    printf("I am functionA!");  
}
void functionB()
{
    printf("I am functionB!");  
}

而对于动态语言,比如Objective-C的下面的代码,在运行的时候,开始调用functionA,还能好好输出I am functionA! 经过一堆奇怪的操作之后,调用functionA 却输出了 I am functionB!

-(void)testEntry{
    [self functionA];  //输出 I am functionA !
    // 下面一堆很奇怪的操作
    Method funA_Method =  class_getInstanceMethod([self class], @selector(functionA));
    Method funB_Method = class_getInstanceMethod([self class], @selector(functionB));
    method_exchangeImplementations(funA_Method, funB_Method);

    [self functionA]; //这里却会输出 I am functionB !
}

-(void)functionA{
    NSLog(@"I am functionA !");
}

-(void)functionB{
    NSLog(@"I am functionB !");
}

这就是动态语言的效果。能够在运行的时候变更代码的执行效果。写好的代码,定义好的对象,在运行的过程中都可能发生改变的。程序跑着跑着,我就不是我了。

Objective-C主要是通过runtime的东西来实现这种动态性的。

本文试着从以下几方面说说runtime的事情:

Objective-C的runtime机制01-重要数据结构和内部关系图
Objective-C的runtime机制02-消息机制
Objective-C的runtime机制03-动态创建和修改类和对象
Objective-C的runtime机制04-category
Objective-C的runtime机制05-常见的使用场景

另外,iOS runtime的源码可以在这里下载阅读:
http://opensource.apple.com/tarballs/objc4/

参考文献

Objective-C Runtime Programming Guide
Objective-C Runtime Reference
《Effective Objective-C 2.0》
《pro multithreading and Management》
南峰子的技术博客-Objective-C Runtime 运行时
王中周的个人博客-Objective-C runtime之运行时
Understanding the Objective-C Runtime
刨根问底Objective-C Runtime
Type Encodings

上一篇 下一篇

猜你喜欢

热点阅读