@interface View: UIView
@property (nonatomic) User* user;
@end
@implement View
- (void)setUser:(User *)user {
_user = user;
[_user addObserver:self forKeyPath:@"name" options:NSKeyValueObservingOptionNew context:nil];
}
- (void) observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context {
NSLog(@"keyPath: %@", keyPath);
NSLog(@"value changed to: %@", [change objectForKey:@"new"]);
}
@end
....
- (void)viewDidLoad {
[super viewDidLoad];
View* view = [View alloc] init];
User* user = [[User alloc] init];
[user setValue:@"haha" forKey:@"name"];
NSLog(@"name = %@", [user valueForKey:@"name"]);
[view setUser:user];
user.name = @"newName";
}
...