您的位置:首页 > 其它

获取对象的属性名、属性值、属性特性,协议列表

2016-02-17 11:37 295 查看
unsigned int count = 0;
//获取属性名
objc_property_t *properties = class_copyPropertyList([self class], &count);
for (int i =0; i < count; i ++) {
const char *propertyName =property_getName(properties[i]);//获取属性名
constchar *propertyAttr =property_getAttributes(properties[i]);//获取属性特性  通常是T@"类型"开头,V_属性名称结尾的格式   可以搜索苹果文档“Property Attribute Description Examples”
id propertyValue = [selfvalueForKey:[NSStringstringWithUTF8String:propertyName]];//获取属性名对应的值,如果是非对象数据返回NSValue类型
NSLog(@"name:%@,attr:%@,value:%@",[NSStringstringWithUTF8String:propertyName],[NSStringstringWithUTF8String:propertyAttr],propertyValue);
}
free(properties);//这里要对取出来的指针数组进行释放,不然会有内存泄露
//获取对象中的变量名
Ivar *vars = class_copyIvarList([self class], &count);
for (int i = 0; i < count; i ++) {
const char *ivarName = ivar_getName(vars[i]);
const char *ivarType = ivar_getTypeEncoding(vars[i]);
}
free(vars);//同样要释放
//获取协议列表
__unsafe_unretained Protocol ** proList= class_copyProtocolList([TestObject class], &count);
for (int i = 0;  i < count; i ++) {
Protocol *pro = proList[i];
const char *name = protocol_getName(pro);//协议名称
NSLog(@"%@",[NSString stringWithUTF8String:name]);
}
free(proList);
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: