[消息传递之七]-KVO练习

来源:互联网 发布:淘宝海外购 编辑:程序博客网 时间:2024/05/19 20:41
#import <UIKit/UIKit.h>@interface ViewController : UIViewController@property (strong, nonatomic) IBOutlet UIButton *btnKVO;@property (strong, nonatomic) IBOutlet UIButton *btnDelete;@property (strong, nonatomic) IBOutlet UIButton *btnResume;- (IBAction)ResumeClick:(UIButton *)sender;- (IBAction)KVOClick:(UIButton *)sender;- (IBAction)DeleteClick:(UIButton *)sender;@end
#import "ViewController.h"#import "TestKVO.h"@interface ViewController ()@end@implementation ViewController{    TestKVO* t;    NSInteger money;}- (void)viewDidLoad {    [super viewDidLoad];    t =[[TestKVO alloc] init];    money = 20;    self.btnDelete.enabled = NO;    self.btnKVO.enabled = false;    // Do any additional setup after loading the view, typically from a nib.}-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context{    if ([keyPath compare:@"HaveMoney" ] == NSOrderedSame) {        NSString* str = (__bridge NSString*)context;        NSLog(@"Money is %ld,Context is %@",[object HaveMoney],str);        if (change) {            [change enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {                NSLog(@"key is %@, obj is %@",key,obj);            }];        }    }    else    {        [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];    }}- (void)didReceiveMemoryWarning {    [super didReceiveMemoryWarning];    // Dispose of any resources that can be recreated.}- (IBAction)KVOClick:(UIButton *)sender {    t.HaveMoney = money;    money++;}- (IBAction)DeleteClick:(UIButton *)sender {    [t removeObserver:self forKeyPath:@"HaveMoney"];    self.btnResume.enabled = YES;    self.btnDelete.enabled = NO;    self.btnKVO.enabled = NO;}- (IBAction)ResumeClick:(UIButton *)sender {    [t addObserver:self forKeyPath:@"HaveMoney" options:NSKeyValueObservingOptionNew context:@"hello"];    self.btnKVO.enabled = YES;    self.btnDelete.enabled = YES;    self.btnResume.enabled = NO;}@end

1,可以重复添加,添加后也是重复执行,这点要注意。

2,删除一次后,就不能重复删除了,不清楚如何检测自己的observer。

3,要响应父类的,删除的时候,可以利用context的值,看看是否本类注册的。

0 0