zoukankan      html  css  js  c++  java
  • IOS疯狂基础之观察者模式

    转自:http://blog.csdn.net/wudizhukk/article/details/8981535

    一、KVO

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

    model中的定义:

    复制代码
    @interface StockData : NSObject {
        NSString * stockName;
        float price;
    }
    @end
    @implementation StockData
    @end
    复制代码

    controller中使用,记得上一篇怎么说的吗?这里相当于跟模型说,我要收听你的更新广播

    复制代码
    - (void)viewDidLoad
    {
        [super viewDidLoad];
    
        stockForKVO = [[StockData alloc] init];
        [stockForKVO setValue:@"searph" forKey:@"stockName"];
        [stockForKVO setValue:@"10.0" forKey:@"price"];    
        [stockForKVO addObserver:self forKeyPath:@"price" options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld context:NULL];
    
        myLabel = [[UILabel alloc]initWithFrame:CGRectMake(100, 100, 100, 30 )];
        myLabel.textColor = [UIColor redColor];
        myLabel.text = [stockForKVO valueForKey:@"price"];
        [self.view addSubview:myLabel];
       
        UIButton * b = [UIButton buttonWithType:UIButtonTypeRoundedRect];
        b.frame = CGRectMake(0, 0, 100, 30);
        [b addTarget:self action:@selector(buttonAction) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:b];
    
    }
    复制代码

    用户单击View中的button调用控制器中的action去更改模型中的数据

    -(void) buttonAction
    {
        [stockForKVO setValue:@"20.0" forKey:@"price"];
    }

    控制器需要实现的回调,相当于收到广播后我应该做啥事

    复制代码
    -(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
    {
        if([keyPath isEqualToString:@"price"])
        {
            myLabel.text = [stockForKVO valueForKey:@"price"];
        }
    }
    复制代码

    视图dealloc需要取消观察

    - (void)dealloc
    {
        [super dealloc];
        [stockForKVO removeObserver:self forKeyPath:@"price"];
        [stockForKVO release];
    }

    二、Notification

    通知使用起来非常的简单:

    首先定义回调,即发生通知了我应该做啥事。

    - (void)callBack{
        NSLog(@"我收到通知了!");
    }

    其次,注册通知,即告诉通知中心,我对啥通知感兴趣

    [[NSNotificationCenter defaultCenter] addObserver: self
        selector: @selector(callBack)
        name: @"A类通知"
        object: nil];

    第三,在程序任何一个地方都可以发送通知

    - (void)getNotofocation{
        NSLog(@"get it.");
        //发出通知
        [[NSNotificationCenter defaultCenter] postNotificationName:@"A类通知" object:self];
    }

    当然,也可以在需要的时候取消注册通知。

  • 相关阅读:
    python中的BeautifulSoup使用小结
    python数字前自动补零
    python列表中的所有值转换为字符串,以及列表拼接成一个字符串
    python爬虫requests过程中添加headers
    django+mysql简单总结
    python数字转换为字符串的两种方式
    python自带的IDLE如何清屏
    django模板中的自定义过滤器
    python中的requests使用小结
    在非UI线程中自制Dispatcher
  • 原文地址:https://www.cnblogs.com/LCGIS/p/3337587.html
Copyright © 2011-2022 走看看