ios的消息通知时通过一个消息中心来负责发送的
现在给一个 国王发送圣旨给 农民和工人的例子
=====================================
King类
#import "King.h"
@implementation King
-(void)SendMess
{
NSLog(@"圣旨发出");
//创建通知对象 通知的名字是: NOTIFICATIONNAME
NSNotification *notify = nil;
notify = [NSNotification notificationWithName:@"NOTIFICATIONNAME" object:self userInfo:[NSDictionary dictionaryWithObject:@"孩儿们 要征税了 水深火热去吧!" forKey:@"order"]];
//消息中心 发送通知
[[NSNotificationCenter defaultCenter] postNotification:notify];
}
@end
=====================================
Worker类
#import "Worker.h"
@implementation Worker
-(id)init
{
if(self = [super init])
{
//注册监听者 通知的名字是: NOTIFICATIONNAME
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(receiveMes:) name:@"NOTIFICATIONNAME" object:nil];
}
return self;
}
-(void)receiveMes:(NSNotification *)notify
{
//接收到消息中心送来的 用户信息
NSDictionary *dic = [notify userInfo];
NSLog(@"Worker:收到信息:%@",[dic objectForKey:@"order"]);
}
-(void)dealloc
{
//除移通知 通知的名字是: NOTIFICATIONNAME
[[NSNotificationCenter defaultCenter] removeObserver:self forKeyPath:@"NOTIFICATIONNAME" context:nil];
[super release];
}
@end
=====================================
Farmer类 (和Worker类是一样的)
#import "Farmer.h"
@implementation Farmer
-(id)init
{
if(self=[super init])
{
//注册监听者 通知的名字是: NOTIFICATIONNAME
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(receiveMsg:) name:@"NOTIFICATIONNAME" object:nil];
}
return self;
}
-(void)receiveMsg:(NSNotification *)notify
{
NSDictionary *dic = [notify userInfo];
NSLog(@"Farmer:收到信息:%@",[dic objectForKey:@"order"]);
}
-(void)dealloc
{
//除移通知 通知的名字是: NOTIFICATIONNAME
[[NSNotificationCenter defaultCenter] removeObserver:self forKeyPath:@"NOTIFICATIONNAME" context:nil];
[super dealloc];
}
@end
#import <Foundation/Foundation.h>
#import "King.h"
#import "Worker.h"
#import "Farmer.h"
int main(int argc, const char * argv[])
{
@autoreleasepool {
King *king = [King new];
Farmer *farmer = [Farmer new];//new 等价于 alloc init 所以会执行到 重写的init方法
Worker *work = [Worker new]; //new 等价于 alloc init 所以会执行到 重写的init方法
[king SendMess];
}
return 0;
}
2013-08-20 15:25:38.559 demo[3665:303] 圣旨发出
2013-08-20 15:25:38.561 demo[3665:303] Farmer:收到信息:孩儿们 要征税了 水深火热去吧!
2013-08-20 15:25:38.562 demo[3665:303] Worker:收到信息:孩儿们 要征税了 水深火热去吧!