**ViewController**
#import "ViewController.h"
#import "Person.h"
@interface ViewController ()
@property (nonatomic, retain) Person *person;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
[self.view setValue:[UIColor orangeColor] forKey:@"backgroundColor"];
self.person = [[Person alloc]init];
[self.person setValue:@"林翰" forKey:@"name"];
[self.person setValue:@"23" forKeyPath:@"age"];
[self.person addObserver:self forKeyPath:@"name" options:NSKeyValueObservingOptionNew context:@"觀察Person的name值"];
}
- (IBAction)kvoButton:(UIButton *)sender {
[self.person setValue:@"大哥" forKey:@"name"];
}
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context {
NSLog(@"\n\n\n");
if ([keyPath isEqualToString:@"name"]) {
NSLog(@"keyPath = %@", keyPath);
NSLog(@"object = %@", object);
NSLog(@"change = %@", change);
NSLog(@"context = %@", context);
}
}
**Person 類**
person.h文件裏
#import <Foundation/Foundation.h>
#import "Student.h"
@interface Person : NSObject
@property (nonatomic, copy) NSString *name; /**< Preson姓名 */
@property (nonatomic, assign) NSInteger age; /**< 年齡 */
@end