廢話不多說,直接進入主題。Runtime 是一套用 C 和匯編編寫的動態庫,就像一個微型的操作系統,把 Objective-C 和 C 緊緊關聯在一起。這個系統主要做兩件事:
換句話說,我們寫下的每一行 OC 代碼,在運行時都會被轉換成 runtime 的消息表達式。學習 runtime 能幫助我們真正理解 OC 的消息發送機制,我認為這是深入 iOS 必須跨過的一道坎——比如當你閱讀一些優秀的第三方框架時,會發現裡面大量使用了運行時代碼。
那麼掌握 runtime 之後,我們能做一些什麼?
聽起來簡直像黑魔法——事實上 runtime 素有「黑魔法」之稱。那就從成員變量開始吧。
成員變量是我們定義一個類時非常重要的組成部分,用來描述這個類實例化之後具備哪些屬性和特點。比如定義一個 Person 類,用 name、age、gender 等屬性來描述它。但這只說明了「有什麼用」,還沒說清「本質是什麼」。
在 runtime.h 中,成員變量是一個指向 objc_ivar 結構體的指針:
/// An opaque type that represents an instance variable. typedef struct objc_ivar *Ivar;
objc_ivar 的結構體定義如下:
struct objc_ivar {
char *ivar_name OBJC2_UNAVAILABLE; //成員變量的名字
char *ivar_type OBJC2_UNAVAILABLE; //成員變量的類型
int ivar_offset OBJC2_UNAVAILABLE;
#ifdef __LP64__
int space OBJC2_UNAVAILABLE;
#endif
}
操作成員變量的常用函數有這幾個:
Ivar *class_copyIvarList(Class cls, unsigned int *outCount) //獲取所有成員變量 const char *ivar_getName(Ivar v) //獲取某個成員變量的名字 const char *ivar_getTypeEncoding(Ivar v) //獲取某個成員變量的類型編碼 Ivar class_getInstanceVariable(Class cls, const char *name) //獲取指定名稱的成員變量 id object_getIvar(id obj, Ivar ivar) //獲取對象中某個成員變量的值 void object_setIvar(id obj, Ivar ivar, id value) //設置對象中某個成員變量的值
先定義一個 Person 類,並重寫它的 description 方法。
Person.h:
@interface Person : NSObject {
NSString *clan; //族名
}
@property(nonatomic,copy)NSString *name;
@property(nonatomic,copy)NSString *gender;
@property(nonatomic,strong)NSNumber *age;
@property(nonatomic,assign)NSInteger height;
@property(nonatomic,assign)double weight;
Person.m:
-(NSString *)description {
unsigned int outCount;
Ivar *IvarArray = class_copyIvarList([Person class], &outCount);//獲取到Person中的所有成員變量
for (unsigned int i = 0; i < outCount; i ++) {
Ivar *ivar = &IvarArray[i];
NSLog(@"第%d個成員變量:%s,類型是:%s", i, ivar_getName(*ivar), ivar_getTypeEncoding(*ivar));
}
return nil;
}
在程序入口創建 Person 實例並調用 description,控制台便會打印:

ivar_getTypeEncoding 拿到的是類型編碼,這是蘋果對數據類型與對象類型的另一種表達方式,例如 @ 代表對象,: 表示 SEL 指針,v 表示 void。具體規定可查閱蘋果官方文檔。
Person.m 中實現兩個方法,一個負責賦值,一個負責取值:
+ (Person *)personWithName:(NSString *)name age:(NSNumber *)age gender:(NSString *)gender clan:(NSString *)clan {
Person *p = [Person new];
unsigned int outCount;
Ivar *IvarArray = class_copyIvarList([Person class], &outCount);
object_setIvar(p, IvarArray[0], clan);
object_setIvar(p, IvarArray[1], name);
object_setIvar(p, IvarArray[2], gender);
object_setIvar(p, IvarArray[3], age);
return p;
}
- (void)personGetPersonMessage {
unsigned int outCount;
Ivar *IvarArray = class_copyIvarList([Person class], &outCount);
for (NSInteger i = 0; i < 4; i ++) {
NSLog(@"%s = %@", ivar_getName(IvarArray[i]), object_getIvar(self, IvarArray[i]));
}
}
在 viewDidLoad 中調用:
Person *person = [Person personWithName:@"張三" age:@26 gender:@"man" clan:@"漢"]; [person personGetPersonMessage];
控制台打印結果:

成功完成了對 Person 對象的賦值與取值操作。
屬性在 runtime 中的定義如下:
/// An opaque type that represents an Objective-C declared property.
typedef struct objc_property *objc_property_t;
/// Defines a property attribute
typedef struct {
const char *name; /**< The name of the attribute */
const char *value; /**< The value of the attribute (usually empty) */
} objc_property_attribute_t;
屬性的本質同樣是一個結構體指針,指向 objc_property。runtime 為屬性準備了一系列操作函數:
objc_property_t *class_copyPropertyList(Class cls, unsigned int *outCount) //獲取所有屬性的列表 const char *property_getName(objc_property_t property) //獲取某個屬性的名字 const char *property_getAttributes(objc_property_t property) //獲取屬性的特性描述 objc_property_attribute_t *property_copyAttributeList(objc_property_t property, unsigned int *outCount) //獲取所有屬性的特性
Person.m 中獲取所有屬性的特性描述:
- (void)getAttributeOfproperty {
unsigned int outCount;
objc_property_t *propertyList = class_copyPropertyList([Person class], &outCount);
for (NSInteger i = 0; i < outCount; i ++) {
NSLog(@"屬性:%s,它的特性描述:%s", property_getName(propertyList[i]), property_getAttributes(propertyList[i]));
}
}
注意:獲取屬性列表只會返回用 @property 聲明過的變量,因此 clan 這個成員變量不會出現。打印結果如下:

特性描述主要說明該屬性的修飾符,含義如下:
屬性類型 name值:T value:變化 編碼類型
name值:C(copy) &(strong) W(weak) 空(assign) 等 value:無
非/原子性 name值:空(atomic) N(Nonatomic) value:無
在運行時,runtime 可以拿到所有的成員變量,包括類的私有變量。這也是 runtime 最重要的兩個應用場景:字典轉模型與複雜對象歸檔。
常規做法需要類遵循 <NSCoding> 協議,重寫編碼與解碼兩個方法,然後逐一對每個成員變量進行編解碼。而借助 runtime,我們可以先拿到變量名,再用循環批量處理,代碼量瞬間縮減。以 Person 類為例:
Person.m:
-(instancetype)initWithCoder:(NSCoder *)aDecoder {
self = [super init];
if (self) {
unsigned int outCount;
Ivar *ivarList = class_copyIvarList([Person class], &outCount);
for (NSInteger i = 0; i < outCount; i ++) {
Ivar ivar = ivarList[i];
NSString *ivarName = [NSString stringWithUTF8String:ivar_getName(ivar)];
[self setValue:[aDecoder decodeObjectForKey:ivarName] forKey:ivarName];
}
}
return self;
}
-(void)encodeWithCoder:(NSCoder *)aCoder {
unsigned int outCount;
Ivar *ivarlist = class_copyIvarList([self class], &outCount);
for (NSInteger i = 0; i < outCount; i ++) {
Ivar ivar = ivarlist[i];
NSString *ivarName = [NSString stringWithUTF8String:ivar_getName(ivar)];
[aCoder encodeObject:[self valueForKey:ivarName] forKey:ivarName];
}
}
思路很直白:先用 class_copyPropertyList 拿到所有屬性,再用 property_getName 取出屬性名作為 key,然後去字典裡查有沒有對應的 value,有的話就賦值。
以上操作都是「讀取對象已有屬性的信息」。除此之外,runtime 還能動態添加變量,也就是關聯對象。
還記得分類(Category)和擴展(Extension)的區別嗎?擴展可以為類添加屬性和方法,而分類只能添加方法。這裡有一道經典面試題:不使用繼承,如何給系統類添加一個公共變量?我們知道在擴展裡添加的變量是私有的,外界無法訪問。了解 runtime 的人大概已經猜到,這題考的就是關聯對象。
runtime 提供了三個函數:
void objc_setAssociatedObject(id object, const void *key, id value, objc_AssociationPolicy policy) //為某個對象關聯另一個對象 id objc_getAssociatedObject(id object, const void *key) //獲取某個對象的關聯對象 void objc_removeAssociatedObjects(id object) //移除已關聯的對象
參數說明:
object:要添加成員變量的對象 key:添加成員變量對應的 key 值 value:要添加的成員變量 policy:添加的成員變量的修飾符
以給 NSDictionary 添加一個 NSString 類型的公共變量 funnyName 為例。
NSDictionary 分類 MyDict.h 中新增兩個屬性,一個字符串、一個 block:
@property(nonatomic,copy)NSString *funnyName; @property(nonatomic,copy)void(^dictAction)(NSString *str);
如果只聲明這些變量,在外部使用時會報錯,需要我們手動實現 setter 與 getter。(注意:報錯並不是因為 @property 沒有自動生成存取方法,而是分類無法添加成員變量。)
-(void)setFunnyName:(NSString *)funnyName {
objc_setAssociatedObject(self, @selector(funnyName), funnyName, OBJC_ASSOCIATION_COPY_NONATOMIC);
}
-(NSString *)funnyName {
return objc_getAssociatedObject(self, @selector(funnyName));
}
-(void)setDictAction:(void (^)(NSString *))dictAction {
objc_setAssociatedObject(self, @selector(dictAction), dictAction, OBJC_ASSOCIATION_COPY_NONATOMIC);
}
-(void (^)(NSString *))dictAction {
return objc_getAssociatedObject(self, @selector(dictAction));
}
這樣一來,字典就擁有了兩個新屬性:
NSDictionary *dict = [NSDictionary new];
dict.funnyName = @"SoFunny";
NSLog(@"dict.funnyName = %@", dict.funnyName);
void(^action)(NSString *str) = ^(NSString *str){
NSLog(@"打印了這個字符串:%@", str);
};
//設置block
dict.dictAction = action;
//調用dict的action
dict.dictAction(@"新增加變量dicAction");
控制台成功打印出我們期望的內容:

初窺 runtime,若有表述不當之處,還請各位前輩指正。後續我會繼續更新 runtime 的學習筆記。