成員變量
1、成員變量的定義
Ivar: 實例變量類型,是一個指向objc_ivar結構體的指針typedef struct objc_ivar *Ivar;
2、相關函數
// 獲取所有成員變量class_copyIvarList// 獲取成員變量名ivar_getName// 獲取成員變量類型編碼ivar_getTypeEncoding// 獲取指定名稱的成員變量class_getInstanceVariable// 獲取某個對象成員變量的值object_getIvar// 設置某個對象成員變量的值object_setIvar
說明:
property_getAttributes函數返回objc_property_attribute_t結構體列表,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、實例應用
<!--Person.h文件-->@interface Person : NSObject{ NSString *address;}@property(nonatomic,strong)NSString *name;@property(nonatomic,assign)NSInteger age;
//遍歷獲取Person類所有的成員變量IvarList- (void) getAllIvarList { unsigned int methodCount = 0; Ivar * ivars = class_copyIvarList([Person class], &methodCount); for (unsigned int i = 0; i < methodCount; i ++) { Ivar ivar = ivars[i]; const char * name = ivar_getName(ivar); const char * type = ivar_getTypeEncoding(ivar); NSLog(@"Person擁有的成員變量的類型為%s,名字為 %s ",type, name); } free(ivars);}
<!--打印結果-->2016-06-15 20:26:39.412 demo-Cocoa之method swizzle[17798:2565569] Person擁有的成員變量的類型為@"NSString",名字為 address 2016-06-15 20:26:39.413 demo-Cocoa之method swizzle[17798:2565569] Person擁有的成員變量的類型為@"NSString",名字為 _name 2016-06-15 20:26:39.413 demo-Cocoa之method swizzle[17798:2565569] Person擁有的成員變量的類型為q,名字為 _age
屬性
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
3、實例應用
<!--Person.h文件-->@interface Person : NSObject{ NSString *address;}@property(nonatomic,strong)NSString *name;@property(nonatomic,assign)NSInteger age;
//遍歷獲取所有屬性Property- (void) getAllProperty { unsigned int propertyCount = 0; objc_property_t *propertyList = class_copyPropertyList([Person class], &propertyCount); for (unsigned int i = 0; i < propertyCount; i++ ) { objc_property_t *thisProperty = propertyList[i]; const char* propertyName = property_getName(*thisProperty); NSLog(@"Person擁有的屬性為: '%s'", propertyName); }}
<!--打印結果-->2016-06-15 20:25:19.653 demo-Cocoa之method swizzle[17778:2564081] Person擁有的屬性為: 'name'2016-06-15 20:25:19.653 demo-Cocoa之method swizzle[17778:2564081] Person擁有的屬性為: 'age'
應用具體場景
1、Json到Model的轉化
在開發中相信最常用的就是接口數據需要轉化成Model了(當然如果你是直接從Dict取值的話。。。),很多開發者也都使用著名的第三方庫如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(Dict或Array)的處理
嘗試解決以上問題,你也能寫出屬于自己的功能完備的Json轉Model庫。
2、快速歸檔
有時候我們要對一些信息進行歸檔,如用戶信息類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]; }}
3、訪問私有變量
我們知道,OC中沒有真正意義上的私有變量和方法,要讓成員變量私有,要放在m文件中聲明,不對外暴露。如果我們知道這個成員變量的名稱,可以通過runtime獲取成員變量,再通過getIvar來獲取它的值。
方法:
Ivar ivar = class_getInstanceVariable([Model class], "_str1");NSString * str1 = object_getIvar(model, ivar);
寫給看客
對于已入行的程序員來說,刨根問底,挖開底層是突破瓶頸的必經之路。要想要從技術開發的普通工人變成真正的工程師,就必須需要啃下這塊骨頭。
而且在完成這篇文章的過程中,我發現自己之前走了不少彎路。因為底層理解不夠,在擴展學習時深感效率低下,過目即忘。歸根結底是只了解皮毛,無法內化,深入理解開發者的思路。
當然文章也多是個人理解,如有錯誤也請留言指正,共同成長。感謝大家對VEVB武林網的支持。
新聞熱點
疑難解答