天天看点

OC循环渐进:自定义通知NSNotification

在OC中,除了KVO能够监听一个对象属性的变化外,还有NSNotification类能够对对象进行监听,也就是我们的NSNotification类—自定义通知。

自定义通知非常简单,主要为以下三步:

(1)注册监听者

(2)监听中心发送通知

(3)移除监听者

自定义通知实现如下:

1.定义相对应的主席类,军人类,和人民类;当主席发送通知时,军人和人民要做出相对应的反应。

首先定义一个

PrefixHeader.pch

文件,在里面加入以下宏定义:

#define GreetWithPeople @"GreetWithPeople"

建立主席类如下:

President.h 的文件代码如下:

#import <Foundation/Foundation.h>

@interface President : NSObject

- (void)sendNotification;

@end
           

President.m 的文件代码如下:

#import "President.h"
#import "PrefixHeader.pch"

@implementation President

- (void)sendNotification {
    NSLog(@"主席说:\"同志们辛苦了!\"");
    [[NSNotificationCenter defaultCenter] postNotificationName:GreetWithPeople object:nil userInfo:@{@"solider":@"为人民服务!",@"masses":@"首长辛苦了!"}];
}

@end
           

建立军人类如下:

Soldier.h的文件代码如下:

#import <Foundation/Foundation.h>

@interface Soldier : NSObject

@end
           

Soldier.m的文件代码如下:

#import "Soldier.h"
#import "PrefixHeader.pch"

@implementation Soldier

- (id)init {
    if (self = [super init]) {
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(nitificationAction:) name:GreetWithPeople object:nil];
    }
    return self;
}


- (void)nitificationAction:(NSNotification *)notification {
    NSString *message = notification.userInfo[@"solider"];
    NSLog(@"军人说:\"%@\"",message);
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self name:GreetWithPeople object:nil];
}


@end
           

建立人民类如下:

Masses.h的文件代码如下:

#import <Foundation/Foundation.h>

@interface Masses : NSObject

@end
           

Masses.m的文件代码如下:

#import "Masses.h"
#import "PrefixHeader.pch"

@implementation Masses

- (id)init {
    if (self = [super init]) {
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(notificationAction:) name:GreetWithPeople object:nil];
    }
    return self;
}

- (void)notificationAction:(NSNotification *)notification {
    NSString *message = notification.userInfo[@"masses"];
    NSLog(@"群众说:\"%@\"",message);
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self name:GreetWithPeople object:nil];
}

@end
           

2.在main.m文件中实现主席类对象调用发送消息的方法:

main.m 的文件代码如下:

int main(int argc, const char * argv[]) {
    @autoreleasepool {

        Soldier *solider = nil;
        Masses *masses = nil;

        solider = [[Soldier alloc] init];
        masses = [[Masses alloc] init];

        President *prsident = [[President alloc] init];
        [prsident sendNotification];


    }
    return ;
}
           

测试结果如下:

-08-08 :: Demo01[:] 主席说:"同志们辛苦了!"
-08-08 :: Demo01[:] 军人说:"为人民服务!"
-08-08 :: Demo01[:] 群众说:"首长辛苦了!"
           

以上就是一个简单的自定义通知。