年年有"余"

 找回密码
 立即注册

QQ登录

只需一步,快速开始

查看: 2207|回复: 0

通知机制

[复制链接]
  • TA的每日心情
    奋斗
    2022-12-13 21:26
  • 签到天数: 371 天

    [LV.9]以坛为家II

    发表于 2014-5-19 11:37:20 | 显示全部楼层 |阅读模式
    本帖最后由 Sian 于 2014-5-19 11:40 编辑

    通知是一种设计模式,与代理有类似的地方,一般实现分为几个步骤

    1、设置监听

            [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(recive:) name:@"notification" object:nil];

    2、发送通知

            NSDictionary *dic = [NSDictionary dictionaryWithObject:@"value" forKey:@"key"];
       
            [[NSNotificationCenter defaultCenter] postNotificationName:@"notification" object:nil userInfo:dic];

    3、通知响应

            - (void)recive:(NSDictionary *)userInfo
            {
                        NSLog(@"%@", userInfo);
            }

    示例:
    1. @implementation SAViewController
    2. -(id)init
    3. {
    4.     if (self = [super init]){
    5.         self.view.backgroundColor = [UIColor whiteColor];
    6.         
    7.         // 1、设置监听
    8.         [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(recive:) name:@"notification" object:nil];
    9.         
    10.         // 创建一个按钮,当按钮点击时触发通知发送事件
    11.         UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
    12.         button.frame = CGRectMake(10, 50, 50, 30);
    13.         [button setTitle:@"abc" forState:UIControlStateNormal];
    14.         [self.view addSubview:button];
    15.         [button addTarget:self action:@selector(buttonClick) forControlEvents:UIControlEventTouchUpInside];
    16.     }
    17.     return self;
    18. }
    19. - (void)buttonClick
    20. {
    21.    
    22.     // 2、发送通知
    23.     NSDictionary *dic = [NSDictionary dictionaryWithObject:@"value" forKey:@"key"];
    24.    
    25.     [[NSNotificationCenter defaultCenter] postNotificationName:@"notification" object:nil userInfo:dic];
    26. }
    27. // 3、通知响应
    28. - (void)recive:(NSDictionary *)userInfo
    29. {
    30.     NSLog(@"%@", userInfo);
    31. }
    32. @end
    复制代码



    您需要登录后才可以回帖 登录 | 立即注册

    本版积分规则

    手机版|小黑屋|Archiver|iOS开发笔记 ( 湘ICP备14010846号 )

    GMT+8, 2024-5-3 11:52 , Processed in 0.043838 second(s), 19 queries .

    Powered by Discuz! X3.4

    Copyright © 2001-2021, Tencent Cloud.

    快速回复 返回顶部 返回列表