zoukankan      html  css  js  c++  java
  • iOS 项目中的NSNotification简单使用

    iOS中NSNotification的简单使用

    好久没有写过博客了,总是遇到问题查一下,今天查的又是一个老问题,想了想,还是记录一下!今天在项目开发中遇到一个配置及时性处理的问题,想了想之后决定用通知实现,但是实现的时候发现对通知早就忘光了,去网上查了一下,觉得这是一个查过几遍的问题了,觉得有必要自己也记录一下,也算是写一下让自己记得也更加清晰一些!本文只是记录了一下NSNotification的简单使用方法(由于文笔不佳,以后定要常记录一些遇到的问题,数遍能讲出其中的缘由,此过程慢慢努力!)。

    1.NSNotification 是响应式编程

    发送方常用方法:

    // 1.创建通知并发送

    NSNotification *notification = [[NSNotification alloc] initWithName:@"refresh" object:self userInfo:nil] ;

    [[NSNotificationCenter defaultCenter] postNotification:notification];

        // 2.直接发送一个通知名字(不需要额外消息)

    [[NSNotificationCenter defaultCenter] postNotificationName:@"refresh" object:self];

        // 3.发送通知,并单独创建UserInfo

    NSDictionary *userInfo = @{@"name":@"xiaoyou"};

    [[NSNotificationCenter defaultCenter] postNotificationName:@"refresh" object:self userInfo:userInfo];

    接收方常用方法:

    1、 设置监听/*** 添加监听*/-(void)addObserverToNotification{[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateLoginInfo:) name:@"refresh" object:nil];}

    2.监听执行的方法/*** 更新登录信息,注意在这里可以获得通知对象并且读取附加信息*/-(void)updateLoginInfo:(NSNotification *)notification{

    NSDictionary *userInfo=notification.userInfo;

    NSObject *object = notification.object;

    //刷新数据

    [self loadData];

    }

    3、 移除监听-(void)dealloc{//移除监听[[NSNotificationCenter defaultCenter] removeObserver:self];}

    2.注意事项

    接收方在析构方法中必须移除监听,这个是编码规范。

    踏实的学点东西,让自己丰富,也让生活丰富和充实。
  • 相关阅读:
    【大数据云原生系列】大数据系统云原生渐进式演进最佳实践
    Apache Flink on K8s:四种运行模式,我该选择哪种?
    Istio 运维实战系列(2):让人头大的『无头服务』-上
    istio 常见的 10 个异常
    Prometheus Metrics 设计的最佳实践和应用实例,看这篇够了!
    腾讯会议大规模使用Kubernetes的技术实践
    腾讯云推出云原生etcd服务
    Regionals 2014 Asia
    HDU1754 I Hate It splay
    HNOI2002 营业额统计 splay
  • 原文地址:https://www.cnblogs.com/xiaoyouPrince/p/5975761.html
Copyright © 2011-2022 走看看