// Son.m#import "Son.h"@interface Son ()// 将属性放在.m文件中,使之成为私有属性@property (nonatomic, copy) NSString *name;@end
// Father.m#import "Father.h"#import "Son.h"#import@implementation Father#pragma mark - KVC 方式访问和修改私有变量- (void)printSonNameWithKVC{ Son *son = [[Son alloc] init]; // 修改前 NSString *name = [son valueForKey:@"name"]; NSLog(@"-name:%@", name); // 修改后 [son setValue:@"Jabit" forKey:@"name"]; NSString *nameReset = [son valueForKey:@"name"]; NSLog(@"-nameReset:%@", nameReset);}#pragma mark - Runtime 方式访问和修改私有变量- (void)printSonNameWithRuntime{ Son *son = [[Son alloc] init]; unsigned int count = 0; Ivar *members = class_copyIvarList([Son class], &count); for (int i = 0; i < count; i++) { Ivar ivar = members[i]; const char *memberName = ivar_getName(ivar); const char *memberType = ivar_getTypeEncoding(ivar); //依次打印属性名称和属性类型 NSLog(@"%s : %s", memberName, memberType); if (strcmp(memberName, "_name") == 0) { // 修改前 NSString *name = (NSString *)object_getIvar(son, members[i]); NSLog(@"-name:%@", name); // 修改后 object_setIvar(son, members[i], @"Jabit"); NSString *nameReset = (NSString *)object_getIvar(son, members[i]); NSLog(@"-nameReset:%@", nameReset); break; } }}@end