在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"