zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    【例题 6-21 UVA
    【例题 6-20 UVA
    【Codeforces Round #446 (Div. 2) C】Pride
    【Codeforces Round #446 (Div. 2) B】Wrath
    【Codeforces Round #446 (Div. 2) A】Greed
    【例题 6-19 UVA
    【CF675C】Money Transfers(离散化,贪心)
    【CF659E】New Reform(图的联通,环)
    【POJ1276】Cash Machine(多重背包单调队列优化)
    【HDU3507】Print Article(斜率优化DP)
  • 原文地址:https://www.cnblogs.com/luojiao-lx/p/4977187.html
Copyright © 2011-2022 走看看