您的位置:首页 > 移动开发 > IOS开发

iOS 消息通知-NSNotification

2013-08-20 15:26 288 查看
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:收到信息:孩儿们要征税了水深火热去吧!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: