首页 » IOS » iOS 监听回调机制KVO

iOS 监听回调机制KVO

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

2018-01-18 02:01:18阅读(612)


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

    [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,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


最新发布

CentOS专题

关于本站

5ibc.net旗下博客站精品博文小部分原创、大部分从互联网收集整理。尊重作者版权、传播精品博文,让更多编程爱好者知晓!

小提示

按 Ctrl+D 键,
把本文加入收藏夹