runtime獲取類的屬性列表和方法列表

新建一個(gè)Animal類 ?給類添加一些成員變量、屬性、和方法。


在控制器里面使用該類 并 給相應(yīng)的變量賦值 ?

? //獲取類方法和屬性列表

? ? Animal *mal=[[Animal alloc]init];

? ? [malsetValue:@"大象" forKey:@"name"];

? ? [malsetValue:@"陸地" forKey:@"type"];

? ? [malsetValue:@"grayColor" forKey:@"color"];

? ? //屬性

?? ? mal.tName=@"動(dòng)物";

?? ? mal.wailt=@60;


下面 我們就開(kāi)始用runtime來(lái)獲取一下該類的一些成員變量 屬性 和方法列表?

//獲取 屬性 方法? 成員 變量? 列表

-(void)runtimeList:(Animal*)animal

{

? ? unsigned? int ?count;


? ? //獲取屬性列表

? ? objc_property_t? *propertys=class_copyPropertyList([animal class], &count);

? ? for(NSIntegerindex=0; index

? ? {

? ? ? ? constchar* propertyName=property_getName(propertys[index]);

? ? ? ? NSString *name=[NSString stringWithUTF8String:propertyName];

? ? ? ? //打印屬性和對(duì)應(yīng)的值值

? ? ? ? NSLog(@"%@ -------%@",name,[animal valueForKey:name]);

? ? }

? ? free(propertys);


? ? //獲取成員變量列表

? ? Ivar? *ivars=class_copyIvarList([animalclass], &count);

? ? for(NSIntegerindex=0; index

? ? ? ? const? char* ivarName=ivar_getName(ivars[index]);

? ? ? ? NSString *name=[NSString? stringWithUTF8String:ivarName];

? ? ? ? //打印成員變量和值

? ? ? ? NSLog(@"%@---------%@",name ,[animal valueForKey:name]);

? ? }

? ? free(ivars);

? ? //獲取方法列表

? ? Method*methedList=class_copyMethodList([animalclass], &count);

? ? for(NSIntegerindex=0; index

? ? ? ? SEL? methodName=method_getName(methedList[index]);

? ? ? ? constchar* name=sel_getName(methodName);

? ? ? ? NSString *strName=[NSString stringWithUTF8String:name];


? ? ? ? NSLog(@"%@",strName);

? ? }

? ? free(methedList);


? ? //獲取協(xié)議列表

? ? __unsafe_unretained? Protocol ** proList= class_copyProtocolList([animal class], &count);

? ? for(NSIntegerindex=0; index

? ? ? ? Protocol*proName=proList[index];

? ? ? ? constchar*protocolName=protocol_getName(proName);

? ? ? ? NSString *name=[NSString stringWithUTF8String:protocolName];

? ? ? ? NSLog(@"%@",name);

? ? }

}

控制臺(tái) 打印?

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容