iOS運(yùn)行時(shí)獲取對(duì)象的成員變量和成員方法
- 首先導(dǎo)入runtime 頭文件 #import<objc/runtime.h>
2.獲取某個(gè)類的成員變量或則屬性
unsigned int numIvars;//成員變量個(gè)數(shù)
Ivar *vars = class_copyIvarList(NSClassFromString(@"UIView"), &numIvars);
//Ivar *vars = class_copyIvarList([UIView class], &numIvars);
NSString*key = nil;
for(int i =0; i < numIvars; i++) {
Ivar thisIvar = vars[i];
key = [NSString stringWithUTF8String:ivar_getName(thisIvar)];//獲取成員變量的名字
NSLog(@"variable name :%@", key);
key = [NSString stringWithUTF8String:ivar_getTypeEncoding(thisIvar)];//獲取成員變量的數(shù)據(jù)類型
NSLog(@"variable type :%@", key);
}
free(vars);
3.獲取成員函數(shù)
Method*meth =class_copyMethodList(NSClassFromString(@"UIView"), &numIvars);
//Method *meth = class_copyMethodList([UIView class], &numIvars);
for(int i =0; i < numIvars; i++) {
Method thisIvar = meth[i];
SEL sel =method_getName(thisIvar);
const char *name =sel_getName(self);
NSLog(@"zp method :%s", name);
}
free(meth);