1、获得通知中心对象

NSNotificationCenter  *center= [NSNotificationCenter defaultCenter];  //单例实际事获得通知中心的地址

2、监听通知

[center addObserver :监听者 selector:须执行的方法 name:所监听者通知的名称 object:通知发送者];

3、通知中心发布消息

[center PostNotificationName:@"为人民服务" object:某人];

4.移除监听中心

[center removeObserver:self name:@"为人民服务" object:某人];

创建King、Worker、Farmer类,由King发一个自定义通知,Worker和Farmer类监听通知,通知内容为打印“某某为人民服务”。

#import <Foundation/Foundation.h>

@interface King : NSObject

-(void)senfMessage;//创建并发送通知

@end


#import "King.h"

@implementation King

-(void)senfMessage{

//创建通知对象,通知的名字是MESSAGE

NSNotification *notification = nil;

   notification = [NSNotificationnotificationWithName:@"MESSAGE"object:selfuserInfo:nil];

//发送通知

   [[NSNotificationCenterdefaultCenter] postNotification:notification];

NSLog(@"我是国王,我正在给我的子民发送通知");

}

@end


#import <Foundation/Foundation.h>

@interface Worker : NSObject

@property(retain,nonatomic) NSString *name;

-(void)say:(NSNotification *) notif;//收到通知后要做的事

@end


#import "Worker.h"

@implementation Worker

-(id)init{

if (self = [superinit]) {

//注册监听者

       [[NSNotificationCenterdefaultCenter] addObserver:selfselector:@selector(say:) name:@"MESSAGE"object:nil];

       }

returnself;

}

-(void)say:(NSNotification *) notif{//收到通知后要做的事

Worker *wk = [[Workeralloc] init];

   wk.name = @"小麦";

NSLog(@"工人%@说我要为人民服务",wk.name);

   [wk release];

}

-(void)dealloc{//移除通知

   [[NSNotificationCenterdefaultCenter] removeObserver:selfname:@"MESSAGE"object:nil];

   [superdealloc];

}

@end


#import <Foundation/Foundation.h>

@interface Farmer : NSObject

@property(retain,nonatomic) NSString *name;

-(void)say:(NSNotification *) notif;//收到通知后要做的事

@end


#import "Farmer.h"

@implementation Farmer

-(id)init{

if (self = [superinit]) {

//注册监听者

       [[NSNotificationCenterdefaultCenter] addObserver:selfselector:@selector(say:) name:@"MESSAGE"object:nil];

   }

returnself;

}

-(void)say:(NSNotification *) notif{//收到通知后要做的事

Farmer *fa = [[Farmeralloc] init];

   fa.name = @"小明";

NSLog(@"农民%@说我要为人民服务",fa.name);

   [fa release];

}

-(void)dealloc{//移除通知

   [[NSNotificationCenterdefaultCenter] removeObserver:selfname:@"MESSAGE"object:nil];

   [superdealloc];

}

@end


#import <Foundation/Foundation.h>

#import "King.h"

#import "Worker.h"

#import "Farmer.h"

int main(int argc, constchar * argv[])

{

@autoreleasepool {

//对象初始化

Worker *w = [[Workeralloc]init];

Farmer *f = [[Farmeralloc]init];

King *k = [[Kingalloc]init];

       [k senfMessage];//创建并发送通知

       [k release];

       [w release];

       [f release];

   }

return 0;

}