私有属性类 Person.m文件
#import "Person.h"
@interface Person ()
@property (nonatomic, strong) NSString *name;
@property (nonatomic, strong) NSNumber *age;
@property (nonatomic, assign) BOOL gender;
@end
@implementation Person
- (NSString *)description {
return [NSString stringWithFormat:@"%@-%@-%d",_name,_age,_gender];
}
@end
Person *person = [Person new];
unsigned int count = 0;
Ivar *members = class_copyIvarList([Person class], &count);//获取的倒序属性列表
for (int i = 0; i < count; i ++) {
const char *memberName = ivar_getName(members[i]);
NSLog(@"%s",memberName);//属性名带有_前缀,例如_name
Ivar m_name = members[i];
pragma mark -----修改私有属性的值1
object_setIvar(person, m_name, @1);//设置时,对象和基本类型不能相互赋值
NSLog(@"%@",[person description]);
}
pragma mark -----修改私有属性的值2
[person setValue:@"zhangsan" forKey:@"name"];
[person setValue:@"nihao" forKey:@"gender"];//给基本属性赋值对象,不起作用
NSLog(@"%@",[person description]);
objc_property_t *member = class_copyPropertyList([Person class], &count);//正序属性列表
for (int i = 0; i < count; i ++) {
const char *memberName = property_getName(member[i]);
NSLog(@"%s",memberName);// 打印原始属性名
}
网友评论