iOS 消息通知-NSNotification

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

=====================================
main

#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:收到信息:孩儿们 要征税了 水深火热去吧!



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值