一、包含運行時頭文件函數
#import <objc/runtime.h>this
二、獲取某個類的成員變量或則屬性;spa
unsigned int numIvars; //成員變量個數orm
Ivar *vars = class_copyIvarList(NSClassFromString(@"UIView"), &numIvars);get
//Ivar *vars = class_copyIvarList([UIView class], &numIvars);string
NSString *key=nil;it
for(int i = 0; i < numIvars; i++) {class
Ivar thisIvar = vars[i];import
key = [NSString stringWithUTF8String:ivar_getName(thisIvar)]; //獲取成員變量的名字變量
NSLog(@"variable name :%@", key);
key = [NSString stringWithUTF8String:ivar_getTypeEncoding(thisIvar)]; //獲取成員變量的數據類型
NSLog(@"variable type :%@", key);
}
free(vars);
三、獲取成員函數
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(sel);
NSLog(@"zp method :%s", name);
}
free(meth);
例子中使用的UIView類能夠替換成任何自定義的類。更多函數查看<objc/runtime.h> !