KVO的簡單用法

//  Created by wjn on 15/9/30.

//  Copyright © 2015 wlm. All rights reserved.

//


#import "ViewController.h"


@interface ViewController ()


@property (nonatomic, retain) NSString *string;


@end


@implementation ViewController


- (void)dealloc {

    

    // 切記一定要在完成之後移除掉 - ARC一樣

    [self removeObserver:self forKeyPath:@"string"];

    

    [super dealloc];

}


- (void)viewDidLoad {

    [super viewDidLoad];

    // Do any additional setup after loading the view, typically from a nib.

    

    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];

    button.frame = CGRectMake(0, 20, self.view.frame.size.width, 40);

    [button setTitle:@"KVO" forState:UIControlStateNormal];

    [button setBackgroundColor:[UIColor greenColor]];

    

    [button addTarget:self action:@selector(buttonDidPress:) forControlEvents:UIControlEventTouchUpInside];

    

    [self.view addSubview:button];


    

    // KVO 一個類監聽自己的屬性(成員變量)的變化

    // 參數1:觀察者

    // 參數2:要觀察的對象

    // 參數3:一旦發生改變,觀察的結果是取新值還是舊值

    // 參數4:一旦發生改變,可以傳遞的內容

    

    [self addObserver:self forKeyPath:@"string" options:NSKeyValueObservingOptionNew context:@"BOOM"];

}


- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context {

    // 系統的方法

    // 當觀察到的屬性改變之後,自動調用這個方法

    NSLog(@"%@", keyPath);

    NSLog(@"%@", object);

    NSLog(@"%@", change);

    NSLog(@"%@", context);

}


//-(NSMutableArray *)mutableArray {

//    if (!_mutableArray) {

//        self.mutableArray = [NSMutableArray arrayWithObject:@"a"];

//    }

//    return _mutableArray;

//}


- (void)buttonDidPress:(UIButton *)sender {

//    [self.mutableArray addObject:@"a"];

    [self setValue:@"aa" forKey:@"string"];

}


- (void)didReceiveMemoryWarning {

    [super didReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.

}


@end


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章