技术文章分类(180)

技术随笔(11)

ios观察者模式之kvo

首先得先了解KVC,KVC (Key Value Coding),简单来讲,就是给属性设置值的;

KVO,即:Key-Value Observing,它提供一种机制,当指定的对象的属性被修改后,则对象就会接受到通知。

KVO是基于KVC实现的。(常用在股票等需要实时监控得场景)

demo下载:https://github.com/MartinLi841538513/KVO_Demo

核心代码(代码中用到定时器是为了更好得展示效果):

//
//  Book.m
//  KVO
//
//  Created by dongway on 14-8-4.
//  Copyright (c) 2014年 dongway. All rights reserved.
//

#import "Book.h"

@implementation Book

-(id)init{
    if (self = [super init]) {
        count = 0;
    }
    return self;
}

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

    if ([keyPath isEqualToString:@"price"]) {
        NSLog(@"old:%@",[change valueForKey:@"old"]);
        NSLog(@"new:%@",[change valueForKey:@"new"]);
    }else if([keyPath isEqualToString:@"name"]){
        NSLog(@"new name:%@",[change valueForKey:@"new"]);
    }
}

-(void)addObserver{
    
    [self addObserver:self forKeyPath:@"price" options:NSKeyValueObservingOptionOld|NSKeyValueObservingOptionNew context:nil];
    [self addObserver:self forKeyPath:@"name" options:NSKeyValueObservingOptionOld|NSKeyValueObservingOptionNew context:nil];
    timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(changePrice) userInfo:nil repeats:YES];

}

-(void)changePrice{
    count++;
    if (count<10) {
        //只要value的值一改变,就会触发监听方法。达到实时监听的作用
        [self setValue:[NSString stringWithFormat:@"%d",count] forKey:@"price"];
        [self setValue:@"ios bookname" forKey:@"name"];
        NSLog(@"%@",name);
    }else{
        [timer invalidate];
    }
    
}
@end

 

posted @ 2014-08-04 15:14  坤哥MartinLi  阅读(168)  评论(0编辑  收藏  举报