iOS中KVO和NSNotification简单示范

本文主要利用最简单的代码来说明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


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值