序言
現(xiàn)在面試的時候,runtime被面試到的概率為百分之百,所以為了獲得一個更好的工作,薪資更高的工作,非常有必要對runtime有一個全面而深入的理解,本文可以幫助讀者實現(xiàn)這個愿望,詳情請看下文。
一 面試題
1.講一下 OC 的消息機制
- OC中的方法調用其實都是轉成了objc_msgSend函數(shù)的調用,給receiver(方法調用者)發(fā)送了一條消息(selector方法名)
- objc_msgSend底層有3大階段
- 消息發(fā)送(當前類、父類中查找)、動態(tài)方法解析、消息轉發(fā)
2. 什么是Runtime?平時項目中有用過么?
- OC是一門動態(tài)性比較強的編程語言,允許很多操作推遲到程序運行時再進行
- OC的動態(tài)性就是由Runtime來支撐和實現(xiàn)的,Runtime是一套C語言的API,封裝了很多動態(tài)性相關的函數(shù)
- 平時編寫的OC代碼,底層都是轉換成了Runtime API進行調用
3.runtime具體應用
- 利用關聯(lián)對象(AssociatedObject)給分類添加屬性
- 遍歷類的所有成員變量(修改textfield的占位文字顏色、字典轉模型、自動歸檔解檔)
- 交換方法實現(xiàn)(交換系統(tǒng)的方法)
- 利用消息轉發(fā)機制解決方法找不到的異常問題
4.如下代碼執(zhí)行結果
#import <Foundation/Foundation.h>
#import "CSPersion.h"
@interface CSStudent : CSPersion
@end
#import "CSStudent.h"
@implementation CSStudent
- (instancetype)init
{
self = [super init];
if (self) {
NSLog(@"[self class] = %@",[self class]);
NSLog(@"[super class] = %@",[super class]);
NSLog(@"[self superclass] = %@",[self superclass]);
NSLog(@"[super superclass] = %@",[super superclass]);
}
return self;
}
@end
#import <Foundation/Foundation.h>
#import "CSStudent.h"
#import "CSPersion.h"
int main(int argc, const char * argv[]) {
@autoreleasepool {
// insert code here...
CSStudent *student = [[CSStudent alloc] init];
}
return 0;
}
執(zhí)行結果

image.png
5.依舊是上述類,執(zhí)行完如下代碼執(zhí)行結果
#import <Foundation/Foundation.h>
#import "CSStudent.h"
#import "CSPersion.h"
int main(int argc, const char * argv[]) {
@autoreleasepool {
BOOL rs1 = [[NSObject class] isKindOfClass:[NSObject class]];
BOOL rs2 = [[NSObject class] isMemberOfClass:[NSObject class]];
BOOL rs3 = [[CSPersion class] isKindOfClass:[CSPersion class]];
BOOL rs4 = [[CSPersion class] isMemberOfClass:[CSPersion class]];
NSLog(@"rs1 = %d,rs2 = %d,rs3 = %d,rs4 = %d",rs1,rs2,rs3,rs4);
}
return 0;
}
執(zhí)行結果

6.執(zhí)行完如下代碼,打印結果
#import <Foundation/Foundation.h>
@interface CSPersion : NSObject
/** name*/
@property(nonatomic,strong)NSString *name;
- (void)print;
@end
#import "CSPersion.h"
@implementation CSPersion
- (void)print {
NSLog(@"my name is %@",self.name);
}
@end
int main(int argc, const char * argv[]) {
@autoreleasepool {
// insert code here...
id cls = [CSPersion class];
void *obj = &cls;
[(__bridge id)obj print];
}
return 0;
}
運行結果

image.png
7.說說什么是runtime
1.OC 是一個全動態(tài)語言,OC 的一切都是基于 Runtime 實現(xiàn)的平時編寫的OC代碼, 在程序運行過程中, 其實最終都是轉成了runtime的C語言代碼, runtime算是OC的幕后工作者
比如:
OC :
[[Person alloc] init]
runtime :
objc_msgSend(objc_msgSend("Person" , "alloc"), "init")
2.runtime是一套比較底層的純C語言API, 屬于1個C語言庫, 包含了很多底層的C語言API
3.runtimeAPI的實現(xiàn)是用 C++ 開發(fā)的(源碼中的實現(xiàn)文件都是mm),是一套蘋果開源的框架
更多有關runtime文章請看下面
iOS-runtime-API詳解+使用
iOS - runtime -詳解
iOS Runtime原理及使用
iOS - runtime如何通過selector找到對應的 IMP地址(分別考慮類方法和實例方法)
iOS - Runtime之面試題詳解一
iOS runtime的使用場景-實戰(zhàn)篇