テスト_プライベート属性リストの取得/プライベート属性の変更の値

1304 ワード

プライベート属性クラス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);//  

    
}