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的使用
- iOS基础 KVC和KVO
- ios开发kvo模式基础-Key-Value Observing 快速入门
- IOS基础学习笔记三:KVC和KVO数组的整体操作
- iOS开发之基础篇(15)—— KVC、KVO
- iOS基础 - KVC and KVO
- IOS基础之(十四) KVO/KVC
- [ios基础] KVO观察者模式,实用分析
- ios开发kvo模式基础-Key-Value Observing 快速入门
- iOS开发——UI基础-KVO
- IOS开发基础之──单例模式
- ios开发基础知识 - 2
- iOS 的目录操作基础
- IOS开发基础之──MVC模式
- IOS开发基础之──NSLog 输出格式详解
- IOS软件结构基础
- IOS开发基础之──viewDidUnload/dealloc调用分析
- IOS开发基础知识要点
- IOS开发基础之──获取时间示例
- IOS开发基础之──main函数及预编译前缀头文件