iOS 监听回调机制KVO实例

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

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

这个就是注册监听,这个@“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"];

}

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

以下是完整例子代码

//

// 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,span)UILabel* label;

@property(nonatomic,span)UIButton* btn;

@property(nonatomic,span)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,span)NSString* data;

@end

#import "TestBean.h"

@implementation TestBean

@end

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

以上是 iOS 监听回调机制KVO实例 的全部内容, 来源链接: utcz.com/z/339861.html

回到顶部