//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
通知
最新推荐文章于 2023-03-21 18:27:07 发布