runtime獲取屬性和成員變量方法
成員變量
1、成員變量的定義
Ivar: 實(shí)例變量類(lèi)型,是一個(gè)指向objc_ivar結(jié)構(gòu)體的指針 typedef struct objc_ivar *Ivar;
2、相關(guān)函數(shù)
// 獲取所有成員變量 class_copyIvarList // 獲取成員變量名 ivar_getName // 獲取成員變量類(lèi)型編碼 ivar_getTypeEncoding // 獲取指定名稱(chēng)的成員變量 class_getInstanceVariable // 獲取某個(gè)對(duì)象成員變量的值 object_getIvar // 設(shè)置某個(gè)對(duì)象成員變量的值 object_setIvar
說(shuō)明:
property_getAttributes函數(shù)返回objc_property_attribute_t結(jié)構(gòu)體列表,objc_property_attribute_t結(jié)構(gòu)體包含name和value,常用的屬性如下:
屬性類(lèi)型 name值:T value:變化
編碼類(lèi)型 name值:C(copy) &(strong) W(weak)空(assign) 等 value:無(wú)
非/原子性 name值:空(atomic) N(Nonatomic) value:無(wú)
變量名稱(chēng) name值:V value:變化
使用property_getAttributes獲得的描述是property_copyAttributeList能獲取到的所有的name和value的總體描述,如 T@"NSDictionary",C,N,V_dict1
3、實(shí)例應(yīng)用
<!--Person.h文件-->
@interface Person : NSObject
{
NSString *address;
}
@property(nonatomic,strong)NSString *name;
@property(nonatomic,assign)NSInteger age;
//遍歷獲取Person類(lèi)所有的成員變量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擁有的成員變量的類(lèi)型為%s,名字為 %s ",type, name);
}
free(ivars);
}
<!--打印結(jié)果--> 2016-06-15 20:26:39.412 demo-Cocoa之method swizzle[17798:2565569] Person擁有的成員變量的類(lèi)型為@"NSString",名字為 address 2016-06-15 20:26:39.413 demo-Cocoa之method swizzle[17798:2565569] Person擁有的成員變量的類(lèi)型為@"NSString",名字為 _name 2016-06-15 20:26:39.413 demo-Cocoa之method swizzle[17798:2565569] Person擁有的成員變量的類(lèi)型為q,名字為 _age
屬性
1、屬性的定義
objc_property_t:聲明的屬性的類(lèi)型,是一個(gè)指向objc_property結(jié)構(gòu)體的指針 typedef struct objc_property *objc_property_t;
2、相關(guān)函數(shù)
// 獲取所有屬性 class_copyPropertyList 說(shuō)明:使用class_copyPropertyList并不會(huì)獲取無(wú)@property聲明的成員變量 // 獲取屬性名 property_getName // 獲取屬性特性描述字符串 property_getAttributes // 獲取所有屬性特性 property_copyAttributeList
3、實(shí)例應(yīng)用
<!--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);
}
}
<!--打印結(jié)果--> 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'
應(yīng)用具體場(chǎng)景
1、Json到Model的轉(zhuǎn)化
在開(kāi)發(fā)中相信最常用的就是接口數(shù)據(jù)需要轉(zhuǎn)化成Model了(當(dāng)然如果你是直接從Dict取值的話。。。),很多開(kāi)發(fā)者也都使用著名的第三方庫(kù)如JsonModel、Mantle或MJExtension等,如果只用而不知其所以然,那真和“搬磚”沒(méi)啥區(qū)別了,下面我們使用runtime去解析json來(lái)給Model賦值。
原理描述:用runtime提供的函數(shù)遍歷Model自身所有屬性,如果屬性在json中有對(duì)應(yīng)的值,則將其賦值。
核心方法:在NSObject的分類(lèi)中添加方法:
- (instancetype)initWithDict:(NSDictionary *)dict {
if (self = [self init]) {
//(1)獲取類(lèi)的屬性及屬性對(duì)應(yīng)的類(lèi)型
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];
//通過(guò)property_getName函數(shù)獲得屬性的名字
NSString * propertyName = [NSString stringWithCString:property_getName(property) encoding:NSUTF8StringEncoding];
[keys addObject:propertyName];
//通過(guò)property_getAttributes函數(shù)可以獲得屬性的名字和@encode編碼
NSString * propertyAttribute = [NSString stringWithCString:property_getAttributes(property) encoding:NSUTF8StringEncoding];
[attributes addObject:propertyAttribute];
}
//立即釋放properties指向的內(nèi)存
free(properties);
//(2)根據(jù)類(lèi)型給屬性賦值
for (NSString * key in keys) {
if ([dict valueForKey:key] == nil) continue;
[self setValue:[dict valueForKey:key] forKey:key];
}
}
return self;
}
讀者可以進(jìn)一步思考:
如何識(shí)別基本數(shù)據(jù)類(lèi)型的屬性并處理
空(nil,null)值的處理
json中嵌套json(Dict或Array)的處理
嘗試解決以上問(wèn)題,你也能寫(xiě)出屬于自己的功能完備的Json轉(zhuǎn)Model庫(kù)。
2、快速歸檔
有時(shí)候我們要對(duì)一些信息進(jìn)行歸檔,如用戶(hù)信息類(lèi)UserInfo,這將需要重寫(xiě)initWithCoder和encodeWithCoder方法,并對(duì)每個(gè)屬性進(jìn)行encode和decode操作。那么問(wèn)題來(lái)了:當(dāng)屬性只有幾個(gè)的時(shí)候可以輕松寫(xiě)完,如果有幾十個(gè)屬性呢?那不得寫(xiě)到天荒地老.
原理描述:用runtime提供的函數(shù)遍歷Model自身所有屬性,并對(duì)屬性進(jìn)行encode和decode操作。
核心方法:在Model的基類(lèi)中重寫(xiě)方法:
- (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、訪問(wèn)私有變量
我們知道,OC中沒(méi)有真正意義上的私有變量和方法,要讓成員變量私有,要放在m文件中聲明,不對(duì)外暴露。如果我們知道這個(gè)成員變量的名稱(chēng),可以通過(guò)runtime獲取成員變量,再通過(guò)getIvar來(lái)獲取它的值。
方法:
Ivar ivar = class_getInstanceVariable([Model class], "_str1"); NSString * str1 = object_getIvar(model, ivar);
寫(xiě)給看客
對(duì)于已入行的程序員來(lái)說(shuō),刨根問(wèn)底,挖開(kāi)底層是突破瓶頸的必經(jīng)之路。要想要從技術(shù)開(kāi)發(fā)的普通工人變成真正的工程師,就必須需要啃下這塊骨頭。
而且在完成這篇文章的過(guò)程中,我發(fā)現(xiàn)自己之前走了不少?gòu)澛贰R驗(yàn)榈讓永斫獠粔?,在擴(kuò)展學(xué)習(xí)時(shí)深感效率低下,過(guò)目即忘。歸根結(jié)底是只了解皮毛,無(wú)法內(nèi)化,深入理解開(kāi)發(fā)者的思路。
當(dāng)然文章也多是個(gè)人理解,如有錯(cuò)誤也請(qǐng)留言指正,共同成長(zhǎng)。感謝大家對(duì)腳本之家的支持。
- 簡(jiǎn)單好用的iOS導(dǎo)航欄封裝.runtime屬性控制實(shí)例代碼
- OC runtime學(xué)習(xí)筆記之關(guān)聯(lián)對(duì)象
- iOS開(kāi)發(fā)中runtime常用的幾種方法示例總結(jié)
- iOS中Runtime的幾種基本用法記錄
- swift中利用runtime交換方法的實(shí)現(xiàn)示例
- iOS利用Runtime實(shí)現(xiàn)友盟頁(yè)面數(shù)據(jù)統(tǒng)計(jì)的功能示例
- iOS runtime動(dòng)態(tài)添加方法示例詳解
- 詳解Java中Checked Exception與Runtime Exception 的區(qū)別
- Java編程使用Runtime和Process類(lèi)運(yùn)行外部程序的方法
- 將cantk runtime嵌入到現(xiàn)有的APP中的方法
相關(guān)文章
iOS App開(kāi)發(fā)中通過(guò)UIDevice類(lèi)獲取設(shè)備信息的方法
UIDevice最常見(jiàn)的用法就是用來(lái)監(jiān)測(cè)iOS設(shè)備的電量了,然后再實(shí)現(xiàn)電池狀態(tài)通知非常方便,除此之外還有傳感器等信息的獲取,這里我們就來(lái)總結(jié)一下iOS App開(kāi)發(fā)中通過(guò)UIDevice類(lèi)獲取設(shè)備信息的方法:2016-07-07
iOS 9 更新之Safari廣告攔截器(Content Blocker)開(kāi)發(fā)教程
這篇文章主要介紹了iOS 9 更新之Safari廣告攔截器(Content Blocker)開(kāi)發(fā)教程的相關(guān)資料,需要的朋友可以參考下2015-08-08
iOS開(kāi)發(fā)實(shí)現(xiàn)轉(zhuǎn)盤(pán)功能
這篇文章主要為大家詳細(xì)介紹了iOS開(kāi)發(fā)實(shí)現(xiàn)轉(zhuǎn)盤(pán)功能,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2020-04-04
iOS實(shí)現(xiàn)視頻下載并自動(dòng)保存到相冊(cè)功能
這篇文章主要為大家詳細(xì)介紹了ios 視頻下載功能實(shí)現(xiàn),并自動(dòng)保存到相冊(cè),文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2020-02-02
詳解iOS應(yīng)用開(kāi)發(fā)中Core Data數(shù)據(jù)存儲(chǔ)的使用
這篇文章主要介紹了iOS應(yīng)用開(kāi)發(fā)中Core Data數(shù)據(jù)存儲(chǔ)的使用,Core Data可以看作是一個(gè)內(nèi)嵌型數(shù)據(jù)庫(kù)SQLite的iOS專(zhuān)用版本,需要的朋友可以參考下2016-02-02

