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

iOS中KVO和NSNotification简单示范

2015-09-21 23:26 609 查看

本文主要利用最简单的代码来说明KVO和NSNotification的使用方法:

1、KVO
KVO的全称是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");
}
@end
2、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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: