关于KVO工程中用到不到,在此整理备份,以备以后使用
监制观察,即让某个VC成为某个Model的某个值的观察者,当该Model的该值发生变化时,会自动通知该VC,触发相应的方法,比较方便,在某些设计模式中常用。代码如下:
Model中:
@interface Student : NSObject
@property (nonatomic, copy) NSString * name;
@property (nonatomic, copy) NSString * score;
@end
VC中:
#import "ViewController.h"
#import "Student.h"
#define OBSERVER_KEY @"score"
@interface ViewController ()
@property (nonatomic, strong) Student * student;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor = [UIColor redColor];
self.student = [[Student alloc] init];
self.student.name = @"xiaoming";
self.student.score = @"80";
[self.student addObserver:self forKeyPath:OBSERVER_KEY options:NSKeyValueObservingOptionNew context:nil];
}
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context{
NSLog(@"keyPath == %@,\nchange == %@",keyPath,change);
NSLog(@"student name == %@,score == %@,intScore == %ld",self.student.name,self.student.score,self.student.intScore );
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
NSString * newScore = [NSString stringWithFormat:@"%ld",(NSUInteger)arc4random()%100];
self.student.score = newScore;
}
- (void)dealloc{
[self.student removeObserver:self forKeyPath:OBSERVER_KEY context:nil];
}
代码很简单,备份。
详细介绍:
http://lib.youkuaiyun.com/article/ios/53438
http://www.tuicool.com/articles/zeqEFbR