
原文见此。
開始之前建議先讀過 iOS Runtime 基礎篇:iOS 內功篇:runtime。
有朋友面試時被問到這樣一個問題:「你知道成員變量的本質是什麼嗎?」當場就懵了——成員變量的本質?成員變量就是成員變量啊,平時只管用,還有什麼更深層的含義?本文著重介紹 runtime 中成員變量與屬性的定義與操作。
1. 定義
Ivar:實例變量類型,是一個指向 objc_ivar 結構體的指標。
typedef struct objc_ivar *Ivar;
2. 常用操作函數
// 取得所有成員變量 class_copyIvarList // 取得成員變量名 ivar_getName // 取得成員變量類型編碼 ivar_getTypeEncoding // 取得指定名稱的成員變量 class_getInstanceVariable // 取得某個物件成員變量的值 object_getIvar // 設定某個物件成員變量的值 object_setIvar
3. 使用範例
Model 的頭檔宣告如下:
@interface Model : NSObject {
NSString *_str1;
}
@property NSString *str2;
@property (nonatomic, copy) NSDictionary *dict1;
@end取得它的成員變量:
unsigned int outCount = 0;
Ivar *ivars = class_copyIvarList([Model class], &outCount);
for (unsigned int i = 0; i < outCount; i++) {
Ivar ivar = ivars[i];
const char *name = ivar_getName(ivar);
const char *type = ivar_getTypeEncoding(ivar);
NSLog(@"類型為 %s 的 %s", type, name);
}
free(ivars);列印結果:
runtimeIvar[602:16885] 類型為 @"NSString" 的 _str1 runtimeIvar[602:16885] 類型為 @"NSString" 的 _str2 runtimeIvar[602:16885] 類型為 @"NSDictionary" 的 _dict1
1. 定義
objc_property_t:已宣告屬性的類型,是一個指向 objc_property 結構體的指標。
typedef struct objc_property *objc_property_t;
2. 常用操作函數
// 取得所有屬性 class_copyPropertyList // 注意:使用 class_copyPropertyList 並不會取得沒有 @property 宣告的成員變量 // 取得屬性名 property_getName // 取得屬性特性描述字串 property_getAttributes // 取得所有屬性特性 property_copyAttributeList
property_getAttributes 回傳的是 objc_property_attribute_t 結構清單,該結構包含 name 與 value,常見的有:
屬性類型 name 值:T value:變化 編碼類型 name 值:C(copy) &(strong) W(weak) 空(assign) 等 value:無 非/原子性 name 值:空(atomic) N(Nonatomic) value:無 變量名稱 name 值:V value:變化
property_getAttributes 得到的描述,是 property_copyAttributeList 所能取到的所有 name 與 value 的總體摘要,例如 T@"NSDictionary",C,N,V_dict1。
3. 使用範例
unsigned int outCount = 0;
objc_property_t *properties = class_copyPropertyList([Model class], &outCount);
for (unsigned int i = 0; i < outCount; i++) {
objc_property_t property = properties[i];
// 屬性名
const char *name = property_getName(property);
// 屬性描述
const char *propertyAttr = property_getAttributes(property);
NSLog(@"屬性描述為 %s 的 %s", propertyAttr, name);
// 屬性的各項特性
unsigned int attrCount = 0;
objc_property_attribute_t *attrs = property_copyAttributeList(property, &attrCount);
for (unsigned int j = 0; j < attrCount; j++) {
objc_property_attribute_t attr = attrs[j];
const char *name = attr.name;
const char *value = attr.value;
NSLog(@"屬性的描述:%s 值:%s", name, value);
}
free(attrs);
NSLog(@"\n");
}
free(properties);列印結果:
runtimeIvar[661:27041] 屬性描述為 T@"NSString",&,V_str2 的 str2 runtimeIvar[661:27041] 屬性的描述:T 值:@"NSString" runtimeIvar[661:27041] 屬性的描述:& 值: runtimeIvar[661:27041] 屬性的描述:V 值:_str2 runtimeIvar[661:27041] runtimeIvar[661:27041] 屬性描述為 T@"NSDictionary",C,N,V_dict1 的 dict1 runtimeIvar[661:27041] 屬性的描述:T 值:@"NSDictionary" runtimeIvar[661:27041] 屬性的描述:C 值: runtimeIvar[661:27041] 屬性的描述:N 值: runtimeIvar[661:27041] 屬性的描述:V 值:_dict1 runtimeIvar[661:27041]
開發中最常用的場景之一,就是介面資料要轉成 Model(當然,如果你直接從字典取值的話就另說)。很多開發者會使用 JsonModel、Mantle 或 MJExtension 這類知名第三方庫;但如果只會用而不知其所以然,那和「搬磚」也沒什麼區別。下面我們用 runtime 自己解析 JSON 並為 Model 賦值。
原理:用 runtime 提供的函數遍歷 Model 自身所有屬性,若屬性在 JSON 中有對應的值,則賦值。
核心方法(加在 NSObject 的分類中):
- (instancetype)initWithDict:(NSDictionary *)dict {
if (self = [self init]) {
// (1) 取得類的屬性及其對應類型
NSMutableArray *keys = [NSMutableArray array];
NSMutableArray *attributes = [NSMutableArray array];
/*
* 例子
* name = value3 attribute = T@"NSString",C,N,V_value3
* name = value4 attribute = T^i,N,V_value4
*/
unsigned int outCount;
objc_property_t *properties = class_copyPropertyList([self class], &outCount);
for (int i = 0; i < outCount; i++) {
objc_property_t property = properties[i];
// 透過 property_getName 取得屬性的名字
NSString *propertyName = [NSString stringWithCString:property_getName(property) encoding:NSUTF8StringEncoding];
[keys addObject:propertyName];
// 透過 property_getAttributes 取得屬性的名字與 @encode 編碼
NSString *propertyAttribute = [NSString stringWithCString:property_getAttributes(property) encoding:NSUTF8StringEncoding];
[attributes addObject:propertyAttribute];
}
// 立即釋放 properties 指向的記憶體
free(properties);
// (2) 依類型為屬性賦值
for (NSString *key in keys) {
if ([dict valueForKey:key] == nil) continue;
[self setValue:[dict valueForKey:key] forKey:key];
}
}
return self;
}給讀者的延伸思考:
如何識別並處理基本資料類型的屬性
空值(nil、null)的處理
JSON 中嵌套 JSON(Dictionary 或 Array)的處理
把這些問題解決掉,你也能寫出屬於自己、功能完備的 JSON 轉 Model 庫。
我們時常需要對一些資訊做歸檔,例如使用者資訊類 UserInfo。這通常意味著要重寫 initWithCoder: 與 encodeWithCoder:,並為每個屬性分別寫 encode 與 decode。屬性只有幾個時還好,如果有幾十個呢?難不成要寫到天荒地老。
原理:用 runtime 遍歷 Model 自身所有屬性,逐一執行 encode 與 decode。
核心方法(在 Model 的基類中重寫):
- (id)initWithCoder:(NSCoder *)aDecoder {
if (self = [super init]) {
unsigned int outCount;
Ivar *ivars = class_copyIvarList([self class], &outCount);
for (int i = 0; i < outCount; i++) {
Ivar ivar = ivars[i];
NSString *key = [NSString stringWithUTF8String:ivar_getName(ivar)];
[self setValue:[aDecoder decodeObjectForKey:key] forKey:key];
}
}
return self;
}
- (void)encodeWithCoder:(NSCoder *)aCoder {
unsigned int outCount;
Ivar *ivars = class_copyIvarList([self class], &outCount);
for (int i = 0; i < outCount; i++) {
Ivar ivar = ivars[i];
NSString *key = [NSString stringWithUTF8String:ivar_getName(ivar)];
[aCoder encodeObject:[self valueForKey:key] forKey:key];
}
}我們都知道,Objective-C 並沒有真正意義上的私有變量與私有方法。要讓成員變量「私有」,做法是在 .m 檔中宣告而不對外暴露。但只要我們知道變量名稱,就能透過 runtime 取得該成員變量,再用 object_getIvar 取出它的值:
Ivar ivar = class_getInstanceVariable([Model class], "_str1"); NSString *str1 = object_getIvar(model, ivar);
歡迎大家交流探討。