zoukankan      html  css  js  c++  java
  • iOS的通知Notification

    这里是不同的对象之间的通知, 不是本地通知.

    一开始玩, 很挠头, 后来发现原来只是对象init的过程出了问题.

    首先, 新建一个简单的单controller的工程.

    然后打开它的ViewController.m文件

    @interface ViewController ()
    @property  NotifyObserver *obj;    //这里是关键, 应该有一个property是另一个要通知的类的, 我之前写在了viewDidLoad里面, 结果死活通知没有响应, 其实原因是这个对象在viewDidLoad方法完成后就自动销毁了, 还通知个屁.

    @end

    @implementation ViewController

    - (void)viewDidLoad {
        [super viewDidLoad];
       self.obj=[[NotifyObserver alloc] init]; //这里init了一个要通知的对象.

        //NotifyObserver *obj=[[NotifyObserver alloc] init]; 之前是这么写的, 折腾了两个小时, 应该抽自己....
    }

    - (void)didReceiveMemoryWarning {
        [super didReceiveMemoryWarning];
    }

    - (IBAction)notifyButtonPressed:(id)sender {
        NSLog(@"pressed");
        //这里开始通知了, 还留下一个问题是如何拿到userInfo, 先不管, 总之发送了一个名为updateMessage的通知, 内容就是my object.
        NSNotification *notification = [[NSNotification alloc] initWithName:@"updateMessage" object:@"my object" userInfo:@{@"Status": @"Success"}];

        [[NSNotificationCenter defaultCenter] postNotification:notification];

    }

    @end

    谁要接收这个通知, 就要去注册一下

    @implementation NotifyObserver

    -(id)init{
        NSLog(@"init"); 

        //在init方法里面注册自己是一个观察者, 然后定义自己只接收"updateMessage"的通知, 别乱七八糟的啥都通知我, 另外, 如果通知到了, 麻烦运行update方法, 记得后面有个":"意思是自己是带形参的方法, Java母语的人笑而不语
        [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(update:) name:@"updateMessage" object:nil];   
        return self;
    }
    -(void)dealloc{
       //记得这个对象要被销毁时, 要移除注册
       [[NSNotificationCenter defaultCenter] removeObserver:self];
    }

    //这个update方法就是通知的回调, 一旦通知来了, 就麻烦运行这个方法.
    -(void) update :(NSNotification *)notification
    {
        NSLog(@"update");
        NSString* str = (NSString*)[notification object];//这里取出刚刚从过来的字符串
        NSLog(@"%@",str);
    }

    @end

    几乎一天时间学会通知Notification, 够慢的....

    越来越觉得iOS就是简单啊.....

    通知, 委托, 这两个设计模式iOS玩得溜啊...

  • 相关阅读:
    Go 语言简介(下)— 特性
    Array.length vs Array.prototype.length
    【转】javascript Object使用Array的方法
    【转】大话程序猿眼里的高并发架构
    【转】The magic behind array length property
    【转】Build Your own Simplified AngularJS in 200 Lines of JavaScript
    【转】在 2016 年做 PHP 开发是一种什么样的体验?(一)
    【转】大话程序猿眼里的高并发
    php通过token验证表单重复提交
    windows 杀进程软件
  • 原文地址:https://www.cnblogs.com/Montauk/p/5643213.html
Copyright © 2011-2022 走看看