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];
  • 相关阅读:
    private知识笔记
    finalize知识笔记
    java实现队列的练习
    测试知识笔记(2)
    static和final知识笔记
    测试知识笔记(1)
    overloading知识笔记
    windows Copssh + git 搭建git服务器
    Java Servlet规范
    身份证验证JS代码
  • 原文地址:https://www.cnblogs.com/foxmin/p/2591632.html
Copyright © 2011-2022 走看看