如何用KVO观察对象的子对象的属性变化

如何用KVO观察对象的子对象的属性变化?
KVO观察多级对象属性变化

#import 
@interface LKPerson : NSObject

@property (nonatomic,copy) NSString *uid;
@property (nonatomic,copy) NSString *name;
@property (nonatomic,copy) NSString *age;

@end

#import "LKPerson.h"
@implementation LKPerson

@end


#import 
#import "LKPerson.h"

@interface LKHomeModel : NSObject

@property (nonatomic, copy) LKPerson *person;

@end

#import "LKHomeModel.h"

@implementation LKHomeModel

- (instancetype)init
{
    self = [super init];
    if (self) {
        _person = [LKPerson new];
    }
    return self;
}

 ///关联person对象的属性变化
+ (NSSet *)keyPathsForValuesAffectingValueForKey:(NSString *)key{
   NSSet *keySet = [super keyPathsForValuesAffectingValueForKey:key];
   if ([key isEqual:@"person"]) {
       NSSet *set = [NSSet setWithObject:@"_person.age"];
       keySet = [keySet setByAddingObjectsFromSet:set];
    }
    return keySet;
}

@end

 //控制器中
 - (void)viewDidLoad {
    [super viewDidLoad];

    _homeModel = [LKHomeModel new];
    _homeModel.person.age = @"000";

    [_homeModel addObserver:self forKeyPath:@"person" options:NSKeyValueObservingOptionNew context:nil];

    _homeModel.person.age = @"111";
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context{

      NSLog(@"%@",change);
      NSLog(@"person.age === %@",_homeModel.person.age);

 }

你可能感兴趣的:(如何用KVO观察对象的子对象的属性变化)