• IOS 中的KVO模式 观察者模式


    /
    //  KvoObject.h
    //  KVO
    //
    //  Created by lin kang on 16/6/7.
    //  Copyright © 2016年 lin kang. All rights reserved.
    //
    
    #import <Foundation/Foundation.h>
    
    @interface KvoObject : NSObject
    
    @property (nonatomic,retain) NSString *changeStr;
    
    @end
    
    
    
    
    
    
    //
    //  KvoObject.m
    //  KVO
    //
    //  Created by lin kang on 16/6/7.
    //  Copyright © 2016年 lin kang. All rights reserved.
    //
    
    #import "KvoObject.h"
    
    @implementation KvoObject
    @synthesize changeStr = _changeStr;
    
    +(BOOL)automaticallyNotifiesObserversForKey:(NSString *)key{
        //进行手动调用观察者模式 返回NO
        if ([key isEqualToString:@"changeStr"]) {
            return NO;
        }else{
            return [super automaticallyNotifiesObserversForKey:key];
        }
    }
    
    -(NSString *)changeStr{
        if (_changeStr == nil) {
            _changeStr = @"KVO模式";
        }
        return _changeStr;
    }
    
    -(void)setChangeStr:(NSString *)changeStr{
        _changeStr = changeStr;
        //要进行触发观察者模式,需触发这两个方法
        [self willChangeValueForKey:@"changeStr"];
        [self didChangeValueForKey:@"changeStr"];
    }
    @end
    

      

    //
    //  ViewController.m
    //  KVO
    //
    //  Created by lin kang on 16/6/7.
    //  Copyright © 2016年 lin kang. All rights reserved.
    //
    
    #import "ViewController.h"
    #import "AppDelegate.h"
    #import "ViewController1.h"
    
    
    @interface ViewController ()
    {
        AppDelegate *_appDelegate;
        UILabel *_lable;
    }
    @end
    
    @implementation ViewController
    
    - (void)viewDidLoad {
        [super viewDidLoad];
        // Do any additional setup after loading the view.
        _appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
    
        // Do any additional setup after loading the view, typically from a nib.
        UILabel *lb = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 200, 21)];
        lb.center =self.view.center;
        lb.text = _appDelegate.kvoObject.changeStr;
        lb.backgroundColor = [UIColor blueColor];
        _lable = lb;
        [self.view addSubview:lb];
        
        
        UIButton *bt = [UIButton buttonWithType:UIButtonTypeCustom];
        [bt setTitle:@"点我" forState:UIControlStateNormal];
        [bt setBackgroundColor:[UIColor redColor]];
        [bt setFrame:CGRectMake(100, 300, 60, 44)];
        [self.view addSubview:bt];
        [bt addTarget:self action:@selector(btc:) forControlEvents:UIControlEventTouchUpInside];
    
         //注册自己为观察者
        [_appDelegate.kvoObject addObserver:self forKeyPath:@"changeStr" options:(NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld) context:nil];
    }
    
    //接受观察通知
    -(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context{
        NSLog(@"change:%@",change);
        NSString *newStr = [change objectForKey:@"new"];
        _lable.text = newStr;
    //    [self.view setNeedsDisplay];
    }
    
    -(void)btc:(UIButton *)sender{
        ViewController1 *vc1 = [[ViewController1 alloc] init];
        [self.navigationController pushViewController:vc1 animated:YES];
    }
    
    - (void)didReceiveMemoryWarning {
        [super didReceiveMemoryWarning];
        // Dispose of any resources that can be recreated.
    }
    
    @end
    

      

    //
    //  ViewController1.m
    //  KVO
    //
    //  Created by lin kang on 16/6/7.
    //  Copyright © 2016年 lin kang. All rights reserved.
    //
    
    #import "ViewController1.h"
    #import "AppDelegate.h"
    
    @interface ViewController1 ()
    {
        AppDelegate *_appDelegate;
        UILabel     *_lable;
    }
    @end
    
    @implementation ViewController1
    
    - (void)viewDidLoad {
        [super viewDidLoad];
        // Do any additional setup after loading the view.
        _appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
        // Do any additional setup after loading the view, typically from a nib.
        UILabel *lb = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 200, 21)];
        lb.center =self.view.center;
        lb.text = _appDelegate.kvoObject.changeStr;
        lb.backgroundColor = [UIColor blueColor];
        _lable = lb;
        [self.view addSubview:lb];
        
        
        UIButton *bt = [UIButton buttonWithType:UIButtonTypeCustom];
        [bt setTitle:@"改变对象" forState:UIControlStateNormal];
        [bt setBackgroundColor:[UIColor redColor]];
        [bt setFrame:CGRectMake(100, 300, 60, 44)];
        [self.view addSubview:bt];
        [bt addTarget:self action:@selector(changeing:) forControlEvents:UIControlEventTouchUpInside];
        //注册自己为观察者
        [_appDelegate.kvoObject addObserver:self forKeyPath:@"changeStr" options:(NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld) context:nil];
    }
    
    //改变对象
    -(void)changeing:(UIButton *)sender{
        _appDelegate.kvoObject.changeStr = @"我变了,操!";
    }
    
    //接收通知
    -(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context{
        NSLog(@"change:%@",change);
        NSString *newStr = [change objectForKey:@"new"];
        _lable.text = newStr;
    //    [self.view setNeedsDisplay];
    }
    
    - (void)didReceiveMemoryWarning {
        [super didReceiveMemoryWarning];
        // Dispose of any resources that can be recreated.
    }
    
    /*
    #pragma mark - Navigation
    
    // In a storyboard-based application, you will often want to do a little preparation before navigation
    - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
        // Get the new view controller using [segue destinationViewController].
        // Pass the selected object to the new view controller.
    }
    */
    
    @end
    

      所谓观察者模式运用:当对象属性改变是,同时通知多个页面的进行更改。

  • 相关阅读:
    tcp没用吗?为什么MOBA、“吃鸡”游戏不推荐用tcp协议
    这样做动画交互,一点都不费力!
    sql server 小记——分区表(上)
    vs中不得不会的一些小技巧(1)——细说查找
    Aforge.net之旅——开篇:从识别验证码开始
    Redis Hash操作
    Varint 数值压缩
    LevelDB Version
    LevelDB Cache机制
    LevelDB Compaction操作
  • 原文地址:https://www.cnblogs.com/yqlog/p/5567389.html
Copyright © 2020-2023  润新知