1.运行时:在运行的时候,动态获取队形身上的方法,协议,属性,成员变量,可以将对象身上的方法给干掉,弄我们自己的方法
- OC 方法
-(NSArray *)class_copyIvarList{
unsigned int count;
//取类的成员变量class_copyIvarList 方法:class_copyMethodList,类的guan'l:class_copyPropertyList,类的协议class_copyProtocolList
Ivar *ivarList = class_copyIvarList(self.class, &count);
NSMutableArray *mutable = [NSMutableArray array];
for (int i = 0 ; i < count; i++) {
//去ivarList的首地址
Ivar name = ivarList[i];
//属性名
const char *proper = ivar_getName(name);
// 类型
const char *properType = ivar_getTypeEncoding(name);
//属性名转换为utf8
NSString *properName = [NSString stringWithUTF8String:proper];
[mutable addObject:properName];
}
return mutable.copy;
}
- Swift方法
class func printIvarList(clazz:AnyClass) -> [AnyObject]{
var count : UInt32 = 0
let ivars = class_copyIvarList(clazz, &count)
var names = [String]()
for i in 0..<count{
let ivar = ivars[Int(i)]
//名字
let name = ivar_getName(ivar)
let nameString = String(CString: name, encoding: NSUTF8StringEncoding)
names.append(nameString!)
//类型
let type = ivar_getTypeEncoding(ivar)
let typeString = String(CString: type, encoding: NSUTF8StringEncoding)
print("name=\(nameString ?? ""),type =\(typeString ?? "")")
}
return names
}
网友评论