ios - kvo觀察者示例(監(jiān)聽類的屬性變化)

  • 首先創(chuàng)建Person分類

#import <Foundation/Foundation.h>

@interface Person : NSObject



@property (nonatomic, copy) NSString *name;
@property (nonatomic, assign) float height;



@end

  • .m中不做任何事情

  • 控制器.m中


#import "ViewController.h"
#import "Person.h"
@interface ViewController ()

@property (nonatomic, strong) Person *per;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    Person * per = [Person new];
    per.name = @"zhangsan";
    per.height = 1.2;
    self.per = per;
    
    // kvo 為per.name添加觀察者
    [per addObserver:self forKeyPath:@"name" options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld context:nil];
    
    // kvo 為per.height添加觀察者
    [per addObserver:self forKeyPath:@"height" options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld context:nil];
    
}

  • 只要監(jiān)聽的屬性name 和 height的值發(fā)生了改變就會觸發(fā)下面的方法

/** 添加觀察者必須要實(shí)現(xiàn)的方法 */
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context{
    /** 打印新老值 */
    // 從打印結(jié)果看 分別打印出了 name 與 height的新老值
    NSLog(@"old : %@  new : %@",[change objectForKey:@"old"],[change objectForKey:@"new"]);
//    NSLog(@"keypath :  %@",keyPath);
//    NSLog(@"change : %@",change);
    
}

  • 由于對person.name 以及height的屬性都做了監(jiān)聽,只要觸摸后屬性的值發(fā)生改變就做得到通知觸發(fā)通知方法 -(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context 則可以在其內(nèi)部做你想要做的事

/** 觸摸改變per.name屬性值 */
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{

    self.per.name = @"helloworld";
    self.per.height = 3.3;
}


  • 一定要記得移除


/** 移除 */
-(void)dealloc{

    [self.per removeObserver:self forKeyPath:@"name" context:nil];
    [self.per removeObserver:self forKeyPath:@"height" context:nil];

}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end

  • 注意點(diǎn):
    1. 為某個對象的某個屬性添加觀察者,最后一定要移除,否則可能會崩潰
    1. 實(shí)現(xiàn)方法-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context則只要監(jiān)聽的屬性發(fā)生改變就會觸發(fā).
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容