您好,登錄后才能下訂單哦!
這篇文章將為大家詳細講解有關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,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”這篇文章就分享到這里了,希望以上內容可以對大家有一定的幫助,使各位可以學到更多知識,如果覺得文章不錯,請把它分享出去讓更多的人看到。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。