通知(广播)传值

优势

代理传值,属性传值等众多传值方法都是1对1的传值方法,通知(广播)传值是1对多的传值方法,

//第一个控制器视图
#import "FirstViewController.h"

@interface FirstViewController ()

@end

@implementation FirstViewController


- (void)aa
{
    NSLog(@"aaa");
    self.view.backgroundColor = [UIColor redColor];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    
    //关注某个通知
    NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
    
    //此行代码的意义,self关注"捡到200块钱"这个通知 一旦接到了通知,有人发布了"捡到200块钱",self就会执行aa方法
    [center addObserver:self selector:@selector(aa) name:@"捡到200块钱" object:@"李四"];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
//第二个
#import "SecondViewController.h"

@interface SecondViewController ()

@end

@implementation SecondViewController
//
- (IBAction)changeSgin:(id)sender {

    
    
    //在这里我要广播一条信息
    //广播信息 需要使用通知中心(NSNotification)这个类,我们要广播的信息,被称为通知(NSNotification)
    //通知中心是一个单例
    
    NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
    
    //通知中心这个类提供 了广告一条信息的借口,postXXX
    [center postNotificationName:@"捡到200块钱" object:nil userInfo:@{@"key":[UIColor blueColor]}];
    
    
    [center postNotificationName:@"捡到200块钱" object:@"李四" userInfo:nil];
    
    [center postNotificationName:@"征婚" object:@"张三" userInfo:nil];
    
}

- (void)bb:(NSNotification *)notification
{
    NSLog(@"bbb");
    NSLog(@"%@,%@,%@",notification.name,notification.userInfo,notification.object);
    self.view.backgroundColor = [notification.userInfo objectForKey:@"key"];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    
    NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
    
    [center addObserver:self selector:@selector(bb:) name:@"征婚" object:nil];
    
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end

小结:
可参考链接:http://www.cocoachina.com/bbs/read.php?tid-195103.html
http://blog.csdn.net/hitwhylz/article/details/34949151

 posted on 2015-06-13 09:19  ianhao_cn  阅读(183)  评论(0编辑  收藏  举报