iOS--KVO

ViewController.m#

//
//  ViewController.m
//  KVO
//

//

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


@property(nonatomic, strong)Person *person;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
   self.person = [[Person alloc] init];
    
    _person.name = @"dongliang";
    
    //添加觀察者 注冊
    [_person addObserver:self forKeyPath:@"name" options:NSKeyValueObservingOptionNew context:(__bridge void *)self];
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction:)];
    
    [self.view addGestureRecognizer:tap];
    
}

//觀察者的方法
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context{
    
    //keypath 是觀察的屬性
    NSLog(@"---------keypath:%@",keyPath);
    //被觀察的對象
    NSLog(@"---------object:%@",object);
    //新舊值
    NSLog(@"---------change:%@",change);//change是字典
    
    NSLog(@"---------context:%@",context);
    
    if ([change[NSKeyValueChangeNotificationIsPriorKey]boolValue]) {
        NSLog(@"1");
        NSLog(@"值改變之前");
    } else{
        NSLog(@"2");
        NSLog(@"值改變之后");
    }
    

    
//    self.view.backgroundColor = [UIColor greenColor];
    
    //context的作用就是傳值/////////////////////////////
    ViewController *vc = (__bridge ViewController *)context;

    vc.view.backgroundColor = [UIColor greenColor];
}



-(void)tapAction:(UITapGestureRecognizer *)sender{
    
    //我注意你很久了
    _person.name = @"zhaoyu";
    
    
}


/**
 *  移除觀察者!!!!!!!!!!!!!!!!!
 */

-(void)dealloc{
    
    [_person removeObserver:self forKeyPath:@"name"];
}


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

@end

Person.h#

//
//  Person.h
//  KVO
//

//

#import <Foundation/Foundation.h>

@interface Person : NSObject

@property(nonatomic, strong)NSString *name;


@end

Person.m#

//
//  Person.m
//  KVO
//

//

#import "Person.h"

@implementation Person

@end

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

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

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