iOS中访问和修改一个类的私有属性

382 阅读2分钟

访问和修改类的私有属性由一下两种方法实现:

1.通过KVC获取

2.通过runtime访问并修改

定义Person类:

.h文件

#import <Foundation/Foundation.h>

@interface Person : NSObject @property (nonatomic, strong) NSString *name; -(void)sayHello; @end

.m文件

#import "Person.h" @interface Person()

@property (nonatomic,strong) NSString *address;

@end

@implementation Person

-(instancetype)init{ self = [super init]; if (self) { _address = @"三里屯"; self.name = @"张晓"; } return self; }

  • (NSString *)description { return [NSString stringWithFormat:@"我的名字是: %@, 居住在: %@",self.name, self.address]; }

-(void)sayHello{ NSLog(@"hello ,I'm at %@",self.address); } @end

方法一:KVC(键值编码):

Person *onePerson = [[Person alloc]init]; NSLog(@"未修改前: %@",onePerson.description);

[onePerson setValue:@"西二旗" forKey:@"address"]; NSLog(@"通过KVO修改私有属性后:%@",[onePerson description]); 打印结果:

2017-02-14 17:30:43.877 chermon[11436:190372] 未修改前: 我的名字是: 张晓, 居住在: 三里屯 2017-02-14 17:30:43.878 chermon[11436:190372] 通过KVO修改私有属性后:我的名字是: 张晓, 居住在: 西二旗

方法二: 通过runtime:

Person *onePerson = [[Person alloc]init]; NSLog(@"未修改前: %@",onePerson.description);

unsigned int count = 0;

//获取指定类的Ivar列表及Ivar个数
Ivar *member = class_copyIvarList([Person class], &count);

for(int i = 0; i < count; i++){
    Ivar var = member[i];
    //获取Ivar的名称
    const char *memberAddress = ivar_getName(var);
    //获取Ivar的类型
    const char *memberType = ivar_getTypeEncoding(var);
    NSLog(@"address = %s ; type = %s",memberAddress,memberType);
}

//设置实例对象中Ivar的值
object_setIvar(onePerson, member[1], @"海淀区");

NSLog(@"通过runtime修改私有属性后:%@",[onePerson description]);

打印结果: 2017-02-14 17:34:46.388 chermon[11487:193486] 未修改前: 我的名字是: 张晓, 居住在: 三里屯 2017-02-14 17:34:46.389 chermon[11487:193486] address = _name ; type = @"NSString" 2017-02-14 17:34:46.389 chermon[11487:193486] address = _address ; type = @"NSString" 2017-02-14 17:34:46.389 chermon[11487:193486] 通过runtime修改私有属性后:我的名字是: 张晓, 居住在: 海淀区