通知

本文通过一个具体的示例展示了如何在Objective-C中使用通知中心(NSNotificationCenter)来实现不同对象间的解耦通信。示例中定义了King、Worker和Farmer三个类,King通过发布消息,Worker和Farmer作为观察者接收并响应这些消息。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

//King.h
#import <Foundation/Foundation.h>
#import "Worker.h"
#import "Farmer.h"
@interface King : NSObject

-(void)sendMessage;
@end



King.m
#import "King.h"

@implementation King
-(void)sendMessage
{
    NSNotification *notification=nil;
    notification=[NSNotification notificationWithName:@"message" object:self userInfo:[NSDictionary dictionaryWithObject:@"国王万岁" forKey:@"oder"]];
    [[NSNotificationCenter defaultCenter]postNotification:notification];//不要用postNotificationName,这个会重新定义赋值,不会把"国王万岁"发送出去
}
@end



#import "Farmer.h"

@implementation Farmer
-(id)init
{
    if([super init])
    {
        [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(say:) name:@"message" object:nil];
    }
    return self;
}
-(void)say:(NSNotification*)notifica
{
   NSDictionary *d=[noti userInfo];
    NSString *s=[d objectForKey:@"oder"];
    NSLog(@"农民说:%@",s);
}
-(void)dealloc
{
    [[NSNotificationCenter defaultCenter]removeObserver:self name:@"message" object:nil];
}
@end



#import "Worker.h"

@implementation Worker
-(id)init
{
    if([super init])
    {
        [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(say:) name:@"message" object:nil];
    }
         return self;
}
-(void)say:(NSNotification*)noti
{
    NSDictionary *d=[noti userInfo];
    NSString *s=[d objectForKey:@"oder"];
    NSLog(@"工人说:%@",s);
}
-(void)dealloc
{
    [[NSNotificationCenter defaultCenter]removeObserver:self name:@"message" object:nil];
}
@end





#import "ViewController.h"
#import "King.h"
#import "Worker.h"
#import "Farmer.h"
@interface ViewController ()
{
    //定义全局变量
    Worker *w;
    Farmer *f;
}
@end

@implementation ViewController
- (void)viewDidLoad {
    [super viewDidLoad];

   f=[Farmer new];
   w=[Worker new];


    // Do any additional setup after loading the view, typically from a nib.
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
//Button按钮
- (void)ButtonClick:(id)sender {
    King *king=[King new];
    [king sendMessage];
}

@end
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值