iOS中KVO和NSNotification简单示范
2015-09-21 23:26
609 查看
本文主要利用最简单的代码来说明KVO和NSNotification的使用方法:
1、KVOKVO的全称是key value observing,解读为中文就是键值观察者模式,作用呢就是去监控对象的属性,如果属性的值发生了相应的变化,那么就做出相应的操作。下面就通过简单的例子说明:
创建 Single View Application 项目,然后新建一个类,命名为Student,然后在,Student的.h文件中定义出:
#import <Foundation/Foundation.h> @interface Student : NSObject @property (nonatomic, assign) NSInteger age; @end接着在viewController.m文件中:
#import "ViewController.h" #import "Student.h" @interface ViewController () @property (nonatomic , strong) Student *student; @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; _student = [[Student alloc]init]; // 将self(视图控制器)设置为观察者,观察的属性是age,操作(对应变化)为当值改变 [_student addObserver:self forKeyPath:@"age" options:NSKeyValueObservingOptionNew context:nil]; } // 通过添加触摸屏幕发生的方法,来简单地模仿值改变 - (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event { _student.age += 1; } // 这个方法是KVO的核心方法,也就是说对应的值改变后将会调用这个方法,所以想做的对应操作就在这里做 - (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context { NSLog(@"the value is changed"); } @end2、NSNotification
同样创建Single View Application 模板,然后直接在viewController.m文件中写上代码:
#import "ViewController.h" @interface ViewController () @property (nonatomic , strong) UIView *myView; @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; _myView = [[UIView alloc]init]; // 通过创建的通知中心的实例来添加监听者为self(视图控制器),同时添加方法test,讲过这个通知命名为NotificationName,对象设置为nil,通知时就没有对象的限制 [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(test) name:@"NotificationName" object:nil]; } // 通知中添加的方法 - (void)test { NSLog(@"test"); } // 通过触摸屏幕将会触发的方法进行简单测试 - (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event { // 通过通知中心来发送命名为Notification的通知 [[NSNotificationCenter defaultCenter]postNotificationName:@"NotificationName" object:nil userInfo:nil]; } @end
相关文章推荐
- iOS-音频和视频
- IOS沙盒机制的理解
- iOS学习笔记--如何使九宫格布局图片的显示自适应大小
- iOS中的过滤器和正则表达式(NSPredicate,NSRegularExpression)
- iOS激情详解之集合视图
- ios内联函数 inline
- IOS知识点mark
- iOS在文件末尾写入内容
- IOS开发之深拷贝与浅拷贝(mutableCopy与Copy)详解
- 头文件iostream与命名空间namespace
- 文件流: ASCII 与 二进制
- iOS快速缓存之缓存的实现
- iOS视图懒加载问题
- 多线程-GCD
- ios开发系列之文件的写入读取,NSUserDefaults存储数据,NSFileManager操作文件和文件夹
- iOS之浅谈视图控制器的生命周期
- iOS9适配问题
- iOS开发 -- CocoaPods安装和使用步骤(详解)
- iOS开发之地图标注开发
- IOS几种常见的实现扫描、生成二维码的方式(一、使用ZBar SDK)