通知

来源:互联网 发布:淘宝卖家寄错东西骗局 编辑:程序博客网 时间:2024/04/28 00:26
//King.h#import <Foundation/Foundation.h>#import "Worker.h"#import "Farmer.h"@interface King : NSObject-(void)sendMessage;@endKing.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
0 0