• IOS KVO与NSNotificationCenter简单使用


    每次面试都被问到KVO或者通知。今天也自己来看了看通知。

    1、NSNotificationCenter使用。

    使用步骤:添加观察者、发送通知、移除观察者。

    添加观察者:哪里需要接收通知,就在哪里加。例如:

    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(reciveNotfi:) name:@"testNot" object:nil];

     发送通知:

    [[NSNotificationCenter defaultCenter]postNotificationName:@"testNot" object:nil userInfo:@{@"value":dTF.text}];

    接收数据在reciveNotfi处理。

    -(void)reciveNotfi:(NSNotification *)sender{

        NSDictionary *userInfo=sender.userInfo;

        otherLabel.text=[userInfo objectForKey:@"value"];

    }

    移除观察者:

     [[NSNotificationCenter defaultCenter]removeObserver:self name:@"testNot" object:nil];

    注:name必须一致

    参考链接:http://my.oschina.net/u/2340880/blog/406163

    2 KVO

    KVO,即:Key-Value Observing,它提供一种机制,当指定的对象的属性被修改后,则对象就会接受到通知。简单的说就是每次指定的被观察的对象的属性被修改后,KVO就会自动通知相应的观察者了。

    注:一定要是属性,私有变量是不可以的。属性赋值时不能用例如:_count=1;要用self.count=1;否则不生效。

    使用步骤:添加观察者,数据处理,移除观察者

    添加观察者:

    [self addObserver:self forKeyPath:@"count" options:NSKeyValueObservingOptionNew context:nil];

    注:被观察的对象的属性

    数据处理:

    -(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context{

        if ([keyPath isEqualToString:@"count"]) {

        //todo

        }

    }

    移除观察者:

    [self removeObserver:self forKeyPath:@"count"];

    另外附上demo:https://github.com/LingZi123/KVOAndNSNotificationCenter.git

  • 相关阅读:
    字体
    当前li的同级且不包含当前li
    溢出用省略号显示
    .NET Core中使用Cookie步骤
    .NET Core中使用Session步骤
    asp.net core 读取配置
    Asp.Net Core run on Ubuntu
    .net core中使用GB2312编码
    ubuntu mysql 安装
    samba的安装
  • 原文地址:https://www.cnblogs.com/luojiao-lx/p/4977187.html
Copyright © 2020-2023  润新知