码迷,mamicode.com
首页 > 其他好文 > 详细

观察者模式

时间:2015-10-05 16:55:07      阅读:177      评论:0      收藏:0      [点我收藏+]

标签:

#import "ViewController.h"
#import "Person.h"
@interface ViewController ()
@property (nonatomic, strong) Person *model;
@end

@implementation ViewController



- (void)dealloc
{

    
    //第三步:移除观察者 经常会忘记,非常重要 不写的代价就是程序会补丁时间 不定地点的Crash;
    //dealloc 在ARC模式下 一定要写
    
    [self.model removeObserver:self forKeyPath:@"name"];


}


- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.model = [[Person alloc] init];
    self.model.name = @"秦喜军";
//    self.model.delegate = self;
    
    //由self 去观察self.model的name属性是否发生了变化  self.model被观察者
    //第一步 给一个属性添加一个观察者 去观察被观察者的某一个属性
    [self.model addObserver:self forKeyPath:@"name" options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld context:nil];
    
}
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
 self.model.name = @"秦喜君";
}
//- (void)changBankcolor
//{
//    self.view.backgroundColor = [UIColor redColor];
//}

// 第二步:重写observeValue方法,去执行属性改变之后想要做的操作
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
 self.view.backgroundColor = [UIColor redColor];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

观察者模式

标签:

原文地址:http://www.cnblogs.com/mawenqiang/p/4855867.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!