是時(shí)候?qū)憣?xiě)技術(shù)blog了,記錄自己開(kāi)發(fā)過(guò)程中所學(xué)和所得
runtime
是OC作為動(dòng)態(tài)語(yǔ)言很關(guān)鍵的一個(gè)類(lèi)庫(kù)
里面有很多程序運(yùn)行時(shí)調(diào)用的方法
OC黑科技之所在
能動(dòng)態(tài)的對(duì)類(lèi)缠局,變量,方法框杜,協(xié)議進(jìn)行管理和添加
接下來(lái)是一個(gè)簡(jiǎn)單的獲取類(lèi)所有變量的例子:
//存放類(lèi)變量數(shù)量
unsigned int propertyCount
//獲取測(cè)試類(lèi)的變量數(shù)組
objc_property_t *properties = class_copyPropertyList(TestClass, &propertyCount);
//遍歷變量數(shù)組
for (int i =0; i < propertyCount; i++) {
//獲取變量對(duì)象
objc_property_t property = properties[i];
//獲取變量名
const char *propertyName = property_getName(property);
NSString *name = @(propertyName);
unsigned int attributesCount;
//獲取變量屬性數(shù)組
objc_property_attribute_t *attributes = property_copyAttributeList(property, &attributesCount);
//遍歷屬性數(shù)組
for (int x =0; x <attributesCount; x++) {
//屬性對(duì)象
objc_property_attribute_t attribute =attributes[x];
//獲取屬性值
const char *attrValue = property_copyAttributeValue(property, attribute.name);
//屬性名
NSString *attNameStr = @(attribute.name);
//屬性值字符串
NSString *attValueStr = @(attrValue);
//打印一下
NSLog(@"attribute --Name:%@ --Value %@",attNameStr,attValueStr);
}
}
以上是runtime一個(gè)簡(jiǎn)單的使用,對(duì)類(lèi)變量的基礎(chǔ)操作,最近將數(shù)據(jù)導(dǎo)入模型對(duì)象的時(shí)候用到了這些障本,只是OC不支持泛型約束,目前只是編譯器有泛型識(shí)別响鹃,所以將JSON數(shù)據(jù)導(dǎo)入模型時(shí)只能依賴(lài)協(xié)議來(lái)判斷集合中的對(duì)象類(lèi)型驾霜,處理導(dǎo)入集合的數(shù)據(jù)時(shí)會(huì)麻煩一點(diǎn),需要聲明協(xié)議茴迁,目前沒(méi)發(fā)現(xiàn)更好的處理方法.