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玩得溜啊...

  • 相关阅读:
    百度地图api应用
    history的使用
    让img居中的方法
    盒子中得文字居中
    盒子居中问题
    ajax问题
    try{}catch(e){}
    常用的简单js方法
    java工作复习——单选下拉列表——检查单选列表的选项文字是否符合期望
    java工作复习——单选下拉列表——select类
  • 原文地址:https://www.cnblogs.com/Montauk/p/5643213.html
Copyright © 2011-2022 走看看