objective-c 通知(Notification)

  当触发事件发生时,发送通知出去

示例代码:

  当孩子睡眠不好的时候,就会发送通知告诉父亲,孩子快要醒来了

Child.h

#import <Foundation/Foundation.h>
#define CWSTR @"child wake"

@interface Child : NSObject

@property(nonatomic,assign)NSInteger sleep;


@end

Child.m

#import "Child.h"



@implementation Child

-(id)init{
    if (self = [super init]) {
        _sleep = 100;
        [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timeAction:) userInfo:nil repeats:YES];
    }
    return self;
}


-(void)timeAction:(NSTimer *)timer{
    self.sleep --;
    NSLog(@"%@",@(_sleep));
    if (_sleep < 90) {
        [[NSNotificationCenter defaultCenter] postNotificationName:CWSTR object:[NSNumber numberWithInteger:_sleep]];//发送通知
        [timer invalidate];
    }
}

@end

Father.h

#import <Foundation/Foundation.h>
#import "Child.h"
@interface Father : NSObject

-(id)init;

@end

Father.m

#import "Father.h"

@implementation Father

-(id)init{
    if (self = [super init]) {
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(wake) name:CWSTR object:nil];//接受通知
    }
    return self;
}


-(void)wake{
    NSLog(@"知道孩子醒了");
}
@end

main.m

#import <Foundation/Foundation.h>
#import "Child.h"
#import "Father.h"
int main(int argc, const char * argv[])
{

    @autoreleasepool {
        
        // insert code here...
        NSLog(@"Hello, World!");
        
        Father *father = [[Father alloc]init];
        Child *child = [[Child alloc]init];
        
        [[NSRunLoop currentRunLoop] run];
    }
    return 0;
}

运行结果:

2014-01-04 10:14:25.767 通知[788:303] Hello, World!
2014-01-04 10:14:26.769 通知[788:303] 99
2014-01-04 10:14:27.769 通知[788:303] 98
2014-01-04 10:14:28.769 通知[788:303] 97
2014-01-04 10:14:29.769 通知[788:303] 96
2014-01-04 10:14:30.769 通知[788:303] 95
2014-01-04 10:14:31.769 通知[788:303] 94
2014-01-04 10:14:32.769 通知[788:303] 93
2014-01-04 10:14:33.769 通知[788:303] 92
2014-01-04 10:14:34.769 通知[788:303] 91
2014-01-04 10:14:35.769 通知[788:303] 90
2014-01-04 10:14:36.769 通知[788:303] 89
2014-01-04 10:14:36.770 通知[788:303] 知道孩子醒了
Program ended with exit code: 9
原文地址:https://www.cnblogs.com/mo-shou/p/3504574.html