zoukankan      html  css  js  c++  java
  • Cocoa设计模式之通知

      以前觉得通知比较难搞,总是避免。但是折腾一番后发现真的是个好东西,用起来很好。整理下使用方法。

    一、首先,在viewDidLoad或者其他地方添加通知

     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateTable:) name:@"updateTable" object:nil];
    NSNotificationCenter为一个单例模式的类,能调用的方法也比较有限,可以自行查阅api。addobserver:后面的参数为你当前的类,或者你要接收消息的类。selector:收到通知后需要执行的方法。name为通知的名字,object可以作为消息传递的参数。

    二、定义通知完成后所要执行的方法
    - (void)updateTable:(NSNotification *)sender{
        NSLog(@"通知成功");
        
        NSDictionary *dictionary = (NSDictionary *)[sender userInfo];
        NSArray *array = [[NSArray alloc] initWithArray:[dictionary objectForKey:@"names"]];
        
        NSLog(@"%@,%@",[array objectAtIndex:0],[array objectAtIndex:1]);
    }

    sender为发布通知的时候传递过来的参数

    三、在你需要调用方法时发布通知

     [[NSNotificationCenter defaultCenter] postNotificationName:@"updateTable" object:nil userInfo:dictionary];

    dictionary为之前定义的参数

     NSArray *array = [[NSArray alloc] initWithObjects:@"foxbabe",@"philiphu", nil];
        NSDictionary *dictionary = [[NSDictionary alloc] initWithObjectsAndKeys:array,@"names", nil];
  • 相关阅读:
    程序为什么加载到内存中
    cortex-A cortex-R cortex-M处理器的性能比较
    makefile 中的赋值方式
    python(老男孩全栈观后感------文件处理)
    python------lambda(匿名函数)
    python------filter(过滤器)
    Express深入解读
    nodejs安装
    一道有意思的题目
    charAt获取数组,测试
  • 原文地址:https://www.cnblogs.com/foxmin/p/2591632.html
Copyright © 2011-2022 走看看