iOS 监听回调机制KVO实例

时间:2022-09-18 09:51:10

监听某个对象,如果这个对象的数据发生变化,会发送给监听者从而触发回调函数

?
1
[self.bean addObserver:self forKeyPath:@"data" options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld context:NULL];

这个就是注册监听,这个@“data”作为标识符方便回调函数辨认

?
1
2
3
4
5
6
7
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
 if([keyPath isEqualToString:@"data"])
 {
  self.label.text = [self.bean valueForKey:@"data"];
 }
}

这个就是回调函数,分辨是哪个对象发生变化,然后给与相应的处理

?
1
2
3
-(void)viewWillDisappear:(BOOL)animated{
 [self.bean removeObserver:self forKeyPath:@"data"];
}

既然有注册监听还记得解除监听

以下是完整例子代码

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
//
// ViewController.m
// First
//
// Created by shanreal-iOS on 17/10/16.
// Copyright © 2017年 shanreal.LongZhenHao. All rights reserved.
//
#import "ViewController.h"
#import "TestBean.h"
@interface ViewController ()
@property(nonatomic,strong)UILabel* label;
@property(nonatomic,strong)UIButton* btn;
@property(nonatomic,strong)TestBean* bean;
@end
@implementation ViewController
- (void)viewDidLoad {
 [super viewDidLoad];
 // Do any additional setup after loading the view.
 
 self.bean = [[TestBean alloc]init];
 [self.bean setValue:@"1" forKey:@"data"];
 
 self.label = [[UILabel alloc]initWithFrame:CGRectMake(10, 30, 100, 30)];
 self.label.textColor = [UIColor blackColor];
 self.label.text = [self.bean valueForKey:@"data"];
 [self.view addSubview:self.label];
 
 
 self.btn = [[UIButton alloc] initWithFrame:CGRectMake(10, 100, 200, 30)];
 [self.btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
 [self.btn setTitle:@"chanage data" forState:UIControlStateNormal];
 [self.btn addTarget:self action:@selector(clickAction) forControlEvents:UIControlEventTouchUpInside];
 [self.view addSubview:self.btn];
 
}
-(void)viewWillAppear:(BOOL)animated{
 [self.bean addObserver:self forKeyPath:@"data" options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld context:NULL];
 
}
-(void)clickAction{
 int data = [[self.bean valueForKey:@"data"] intValue]+1;
 self.bean.data = [NSString stringWithFormat:@"%d",data];
}
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
 if([keyPath isEqualToString:@"data"])
 {
  self.label.text = [self.bean valueForKey:@"data"];
 }
}
-(void)viewWillDisappear:(BOOL)animated{
 [self.bean removeObserver:self forKeyPath:@"data"];
}
 
@end
 
#import <Foundation/Foundation.h>
@interface TestBean : NSObject{
 NSString* data;
}
@property(nonatomic,assign)int id;
@property(nonatomic,strong)NSString* data;
@end
 
#import "TestBean.h"
@implementation TestBean
@end

以上这篇iOS 监听回调机制KVO实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持服务器之家。

原文链接:http://blog.csdn.net/z979451341/article/details/79086120