RunTime运行时之改变私有属性的值 发表于 2016-10-25 | 分类于 iOS RunTime运行时之改变私有属性的值123456789101112131415161718192021222324252627282930313233343536373839#import "ViewController.h"#import <objc/runtime.h>@interface ViewController (){NSString *str1;}@property (nonatomic, copy) NSString *str2;@end@implementation ViewController- (void)viewDidLoad {[super viewDidLoad];[self changeVarVaule];}#pragma 改变属性值(私有和公开)- (void)changeVarVaule{unsigned int outCount = 0;//获取所有属性列表(包括私有的)Ivar *vars= class_copyIvarList([self class], &outCount);for(int i = 0;i < outCount;i++){//循环取出属性Ivar var = vars[i];if(i == 0){//设置属性的值方式一object_setIvar(self, var, @"piaojin1");}else{//设置属性的值方式二const char *varName = ivar_getName(var);//获取属性名字[self setValue:@"piaojin2" forKey:[NSString stringWithUTF8String:varName]];//通过KVC设置属性值}}NSLog(@"str1:%@,str2:%@",str1,self.str2);}@end ------本文结束😘感谢阅读------