您的位置:首页 > 移动开发 > IOS开发

IOS KVO基础

2017-02-06 17:23 155 查看
- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor = [UIColor whiteColor];
self.student = [Student new];
self.student.name = @"John";
self.student.age = 12;
//添加监听
[self.student addObserver:self forKeyPath:@"name" options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld context:nil];
// Do any additional setup after loading the view.
}
//点击更改监听对象的属性值
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
self.student.name = @"John";
}
//监听值发生变化生成提示框
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context{
if ([keyPath isEqualToString:@"name"]) {
UIAlertController *alertvc = [UIAlertController alertControllerWithTitle:@"提示" message:@"值发生变化了" preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {

}];
[alertvc addAction:action];
[self presentViewController:alertvc animated:YES completion:^{

}];
}
}
- (void)dealloc
{
//注销Observer
[self.student removeObserver:self forKeyPath:@"name"];
}


#import <UIKit/UIKit.h>

@interface TestObserverViewController : UIViewController

@end

@interface model_A : NSObject
@property(nonatomic,strong)NSString *name;
@end
@interface model_B : NSObject

@end

//
//  TestObserverViewController.m
//  Tests
//
//  Created by BOB on 17/4/18.
//  Copyright © 2017年 BOB. All rights reserved.
//

#import "TestObserverViewController.h"

@interface TestObserverViewController ()

@end

@implementation TestObserverViewController

- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor = [UIColor whiteColor];
model_A *ma = [[model_A alloc]init];
model_B *mb = [[model_B alloc]init];
[ma addObserver:mb forKeyPath:@"name" options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld context:nil];
[self delay:2 execute:^{
ma.name = @"bob";
[ma removeObserver:mb forKeyPath:@"name"];
}];
// Do any additional setup after loading the view.
}
-(void)delay:(CGFloat)time execute:(dispatch_block_t)mainqueue_block{
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(time*NSEC_PER_SEC)), dispatch_get_main_queue(), mainqueue_block);
}

@end
@implementation model_A

@end
@implementation model_B

-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context{
NSLog(@"%@",@"hello world");
}

@end
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  ios KVO