编程

当前位置:澳门新莆京娱乐官网 > 编程 > KVO键值观察

KVO键值观察

来源:http://www.drgigabytes.com 作者:澳门新莆京娱乐官网 时间:2020-04-21 12:56
  • Key Value Observing
  • 被阅览者和观看者同一时间实现一个钻探: NSKeyValueObserving
  • 源点设计形式中的观看者形式。
  • 内定被观看对象的属性被改换后,KVO就能自行文告相应的观望者。瞩目:不要遗忘清除注册,不然会促成能源败露
#pragma mark //////////KVO方法////////////注册监听- addObserver:(NSObject *)observer forKeyPath:(NSString *)keyPath options:(NSKeyValueObservingOptions)options context:(nullable void *)context;//移除监听- removeObserver:(NSObject *)observer forKeyPath:(NSString *)keyPath;//监听回调- observeValueForKeyPath:(nullable NSString *)keyPath ofObject:(nullable id)object change:(nullable NSDictionary<NSString*, id> *)change context:(nullable void *)context;

使用KVO

Student.h文件

#import <Foundation/Foundation.h>@interface Student : NSObject@property (nonatomic, copy) NSString *name;@property (nonatomic, assign) NSInteger age;@end

KVOViewController.m文件中1.监听Student的属性

observer: 寓目者对象keyPath: 被调查的品质options: 设定公告观看者时传递的属性值context: 一些其余的内需传递给阅览者的上下文新闻

#import "KVOViewController.h"#import "Student.h"@interface KVOViewController ()@end@implementation KVOViewController{ Student *_student;}- viewDidLoad { [super viewDidLoad]; _student = [[Student alloc] init]; _student.name = @"LuisX"; _student.age = 24; //为属性添加观察者 [_student addObserver:self forKeyPath:@"age" options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld context:NULL]; UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom]; button.frame = CGRectMake(100, 100, 100, 100); button.backgroundColor = [UIColor orangeColor]; [self.view addSubview:button]; [button addTarget:self action:@selector(changeStudentAgeValue:) forControlEvents:UIControlEventTouchUpInside]; }@end

2.点击button修改student的属性

- changeStudentAgeValue:(UIButton *)button{ _student.age++;}

3.兑现监听回调方法

keyPath: 被考查的品质object: 被观望者的靶子change: 属性值,遵照上面提到的Options设置,给出对应的属性值context: 下面传递的context对象

//观察者通过实现下面的方法,完成对属性改变的响应- observeValueForKeyPath:(NSString *)keyPath ofObject:object change:(NSDictionary<NSString *,id> *)change context:context{ if ([keyPath isEqualToString:@"age"] && object == _student) { NSLog(@"age:%ld", _student.age); NSLog(@"old age:%@", [change objectForKey:@"old"]); NSLog(@"new age:%@", [change objectForKey:@"new"]); //输出: age:25 //输出: old age:24 //输出: new age:25 } }

4.移除监听

- viewDidDisappear:animated{ [super viewDidDisappear:animated]; //移除观察者 [_student removeObserver:self forKeyPath:@"age"];}

图片 1Objective-C

本文由澳门新莆京娱乐官网发布于编程,转载请注明出处:KVO键值观察

关键词:

上一篇:二维码及条形码扫描澳门新莆京娱乐官网

下一篇:没有了