不务正业之OC(八)–观察者模式–notification

通知:类和类之间可以相互通讯,存在多对多,不像委托设计一对一,比较清晰,所以在使用类和类通讯时,建议使用委托代理模式

//  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;
        [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timerAction:) userInfo:nil repeats:YES];
    }
    return self;
}
 
- (void) timerAction:(NSTimer *)timer{
    self.wawa--;
    NSLog(@"wawa:%ld",_wawa);
    if (_wawa < 16) {
        //定义通知中心,并发送通知,通知名为weak_up
        [[NSNotificationCenter defaultCenter] postNotificationName:@"weak_up" object:[NSNumber numberWithInteger:_wawa]];
        [timer invalidate];
    }
}
 
@end
//  Mother.h
 
#import <Foundation/Foundation.h>
#import "Baby.h"
 
@interface Mother : NSObject
@end
 
//  Mother.m
 
#import "Mother.h"
 
@implementation Mother
 
- (id) init{
    if(self = [super init]){
        //接收通知者
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(weakNotification:) name:@"weak_up" object:nil];
    }
    return self;
}
//通知接到后,调用方法
- (void)weakNotification:(NSNotification *)notification{
    NSNumber *num = notification.object;
    NSLog(@"Baby weak:%@",num);
}
 
@end
//  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] init];
        [[NSRunLoop currentRunLoop] run];
    }
    return 0;
}

运行结果:

2014-04-30 22:00:19.679 KVO[13898:303] wawa:19
2014-04-30 22:00:20.679 KVO[13898:303] wawa:18
2014-04-30 22:00:21.679 KVO[13898:303] wawa:17
2014-04-30 22:00:22.680 KVO[13898:303] wawa:16
2014-04-30 22:00:23.680 KVO[13898:303] wawa:15
2014-04-30 22:00:23.680 KVO[13898:303] Baby weak:15

Post a Comment