前言
在開始之前建議先閱讀iOS runtime的基礎理解篇:iOS內(nèi)功篇:runtime
有筒子在面試的時候肥矢,遇到這樣一個問題:“你知道成員變量的本質(zhì)是什么嗎?”叠洗,筒子立馬懵逼了甘改,成員變量的本質(zhì)旅东?成員變量就是成員變量啊,平時只管用十艾,還有什么更深層的含義抵代?本文著重介紹runtime中成員變量和屬性的定義和使用。
名詞解析
成員變量
1忘嫉、定義:
Ivar: 實例變量類型荤牍,是一個指向objc_ivar結(jié)構(gòu)體的指針
typedef struct objc_ivar *Ivar;
2、操作函數(shù):
// 獲取所有成員變量
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);
打印結(jié)果:
runtimeIvar[602:16885] 類型為 @"NSString" 的 _str1
runtimeIvar[602:16885] 類型為 @"NSString" 的 _str2
runtimeIvar[602:16885] 類型為 @"NSDictionary" 的 _dict1
屬性
1参淫、定義:
objc_property_t:聲明的屬性的類型,是一個指向objc_property結(jié)構(gòu)體的指針
typedef struct objc_property *objc_property_t;
2愧杯、操作函數(shù):
// 獲取所有屬性
class_copyPropertyList
說明:使用class_copyPropertyList并不會獲取無@property聲明的成員變量
// 獲取屬性名
property_getName
// 獲取屬性特性描述字符串
property_getAttributes
// 獲取所有屬性特性
property_copyAttributeList
說明:
property_getAttributes函數(shù)返回objc_property_attribute_t結(jié)構(gòu)體列表涎才,objc_property_attribute_t結(jié)構(gòu)體包含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);
打印結(jié)果:
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]
應用實例
1、Json到Model的轉(zhuǎn)化
在開發(fā)中相信最常用的就是接口數(shù)據(jù)需要轉(zhuǎn)化成Model了(當然如果你是直接從Dict取值的話跌前。棕兼。。)抵乓,很多開發(fā)者也都使用著名的第三方庫如JsonModel伴挚、Mantle或MJExtension等,如果只用而不知其所以然灾炭,那真和“搬磚”沒啥區(qū)別了茎芋,下面我們使用runtime去解析json來給Model賦值。
原理描述:用runtime提供的函數(shù)遍歷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函數(shù)獲得屬性的名字
NSString * propertyName = [NSString stringWithCString:property_getName(property) encoding:NSUTF8StringEncoding];
[keys addObject:propertyName];
//通過property_getAttributes函數(shù)可以獲得屬性的名字和@encode編碼
NSString * propertyAttribute = [NSString stringWithCString:property_getAttributes(property) encoding:NSUTF8StringEncoding];
[attributes addObject:propertyAttribute];
}
//立即釋放properties指向的內(nèi)存
free(properties);
//(2)根據(jù)類型給屬性賦值
for (NSString * key in keys) {
if ([dict valueForKey:key] == nil) continue;
[self setValue:[dict valueForKey:key] forKey:key];
}
}
return self;
}
讀者可以進一步思考:
1铡原、如何識別基本數(shù)據(jù)類型的屬性并處理
2偷厦、空(nil,null)值的處理
3燕刻、json中嵌套json(Dict或Array)的處理
嘗試解決以上問題只泼,你也能寫出屬于自己的功能完備的Json轉(zhuǎn)Model庫。
2卵洗、快速歸檔
有時候我們要對一些信息進行歸檔请唱,如用戶信息類UserInfo,這將需要重寫initWithCoder和encodeWithCoder方法,并對每個屬性進行encode和decode操作籍滴。那么問題來了:當屬性只有幾個的時候可以輕松寫完酪夷,如果有幾十個屬性呢榴啸?那不得寫到天荒地老孽惰?。鸥印。勋功。
原理描述:用runtime提供的函數(shù)遍歷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];
}
}
3狂鞋、訪問私有變量
我們知道,OC中沒有真正意義上的私有變量和方法潜的,要讓成員變量私有骚揍,要放在m文件中聲明,不對外暴露啰挪。如果我們知道這個成員變量的名稱信不,可以通過runtime獲取成員變量,再通過getIvar來獲取它的值亡呵。
方法:
Ivar ivar = class_getInstanceVariable([Model class], "_str1");
NSString * str1 = object_getIvar(model, ivar);
歡迎大家交流探討抽活。