SoFunction
Updated on 2025-04-12

iOS monitor callback mechanism KVO instance

Listen to an object. If the data of this object changes, it will be sent to the listener to trigger the callback function.

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

This is the registration listening. This @"data" is used as an identifier to facilitate the identification of callback functions.

-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
 if([keyPath isEqualToString:@"data"])
 {
   = [ valueForKey:@"data"];
 }
}

This is the callback function, which distinguishes which object changes and then gives corresponding processing

-(void)viewWillDisappear:(BOOL)animated{
 [ removeObserver:self forKeyPath:@"data"];
}

Since you have registered to listen, remember to release the listener

The following is the complete example code

//
// 
// First
//
// Created by shanreal-iOS on 17/10/16.
// Copyright © 2017. All rights reserved.//
#import ""
#import ""
@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.

  = [[TestBean alloc]init];
 [ setValue:@"1" forKey:@"data"];
 
  = [[UILabel alloc]initWithFrame:CGRectMake(10, 30, 100, 30)];
  = [UIColor blackColor];
  = [ valueForKey:@"data"];
 [ addSubview:];
 
 
  = [[UIButton alloc] initWithFrame:CGRectMake(10, 100, 200, 30)];
 [ setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
 [ setTitle:@"chanage data" forState:UIControlStateNormal];
 [ addTarget:self action:@selector(clickAction) forControlEvents:UIControlEventTouchUpInside];
 [ addSubview:];
 
}
-(void)viewWillAppear:(BOOL)animated{
 [ addObserver:self forKeyPath:@"data" options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld context:NULL];
 
}
-(void)clickAction{
 int data = [[ valueForKey:@"data"] intValue]+1;
  = [NSString stringWithFormat:@"%d",data];
}
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
 if([keyPath isEqualToString:@"data"])
 {
   = [ valueForKey:@"data"];
 }
}
-(void)viewWillDisappear:(BOOL)animated{
 [ removeObserver:self forKeyPath:@"data"];
}

@end

#import <Foundation/>
@interface TestBean : NSObject{
 NSString* data;
}
@property(nonatomic,assign)int id;
@property(nonatomic,strong)NSString* data;
@end

#import ""
@implementation TestBean
@end

The above example of the KVO of iOS monitoring callback mechanism is all the content I share with you. I hope you can give you a reference and I hope you can support me more.