不务正业之OC(七)–KVO介绍–观察者模式

KVO类似数据库中的trigger,就是当属性值发生变化时,能够通知到目标对象(注册者)
定义两个类,Baby.h和Mother.h,当Baby对象对属性wawa发生变化时,Mother对象就能知道

//  Baby.h
#import <Foundation/Foundation.h>
 
@interface Baby : NSObject
@property (nonatomic,assign) NSInteger  wawa;
@end
 
//  Baby.m
#import "Baby.h"
 
@implementation Baby
- (id)init{
    if(self = [super init]){
        self.wawa = 20;
         //定义定时器,每1s触发调用timerAction,wawa实例变量减1
        [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timerAction:) userInfo:nil repeats:YES];
    }
    return self;
}
 
- (void) timerAction:(NSTimer *)timer{
    self.wawa--;
}
@end
//  Mother.h
 
#import <Foundation/Foundation.h>
#import "Baby.h"
 
@interface Mother : NSObject
 
@property(nonatomic,retain) Baby *baby;
 
- (id) initWithBaby:(Baby *)baby;
 
@end
 
//  Mother.m
 
#import "Mother.h"
 
@implementation Mother
 
- (id) initWithBaby:(Baby *)baby{
    if(self = [super init]){
        self.baby = baby;
        //对baby增加一观察者mother,当wawa发生变化时调用observeValueForKeyPath方法
        [self.baby addObserver:self forKeyPath:@"wawa" options:NSKeyValueObservingOptionNew context:nil];
    }
    return self;
}
 
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context{
    NSLog(@"wawa %@",change);
}
 
@end

main.m实现

//  main.m
 
#import <Foundation/Foundation.h>
#import "Mother.h"
 
int main(int argc, const char * argv[])
{
 
    @autoreleasepool {
        Baby *myBaby = [[Baby alloc] init];
        Mother *myMother =[[Mother alloc] initWithBaby:myBaby];
        [[NSRunLoop currentRunLoop] run];
    }
    return 0;
}

执行流程:
1、调用定时器,Baby对象的定时器启动[NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timerAction:) userInfo:nil repeats:YES],触发wawa减1
2、观察者[self.baby addObserver:self forKeyPath:@”wawa” options:NSKeyValueObservingOptionNew context:nil]发现wawa发生变化,调用observeValueForKeyPath

结果:

2014-04-30 20:08:06.646 KVO[13671:303] wawa {
    kind = 1;
    new = 19;
}
2014-04-30 20:08:07.641 KVO[13671:303] wawa {
    kind = 1;
    new = 18;
}
2014-04-30 20:08:08.642 KVO[13671:303] wawa {
    kind = 1;
    new = 17;
}

Post a Comment