观察者模式

2016-05-12  本文已影响16人  小样别嘚瑟

我们先来看看在苹果的Cocoa Touch框架中有谁使用了观察者模式:

1.通知(notification)机制

在通知机制中对某个通知感兴趣的所有对象都可以成为接受者。首先,这些对象需要向通知中心(NSNotificationCenter)发出addObserver:selector:name:object:消息进行注册,在投送对象投送通知送给通知中心时,通知中心就会把通知广播给注册过的接受者。所有的接受者不知道通知是谁投送的,不去关心它的细节。投送对象和接受者是一对多的关系。接受者如果对通知不再关注,会给通知中心发送removeObserver:name:Object:消息解除注册,以后不再接受通知。

(ps:这段话内容摘抄自关东升先生的文章)

我们试着去使用一下通知机制:

新建一个Single view Project,对项目中的文件做以下修改:

AppDelegate.m

- (void)applicationDidEnterBackground:(UIApplication *)application {

[[NSNotificationCenter defaultCenter]postNotificationName:@"APPTerminate" object:self];

}

ViewController.m

//

//  ViewController.m

//  TestNotification

//

//  Created by liwenqian on 14-10-18.

//  Copyright (c) 2014年 liwenqian. All rights reserved.

//

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {

[super viewDidLoad];

//注意此处的selector有参数,要加冒号

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

// Do any additional setup after loading the view, typically from a nib.

}

- (void)didReceiveMemoryWarning {

[super didReceiveMemoryWarning];

[[NSNotificationCenter defaultCenter]removeObserver:self];

// Dispose of any resources that can be recreated.

}

#pragma mark -处理通知

-(void)doSomething:(NSNotification*)notification{

NSLog(@"收到通知");

}

@end

如上所示,对模版项目的两个文件的方法或整个文件做出修改,Command+R运行你的APP,再按下Home键(Command+H),会发现打印出一行收到通知的文字,如下:

  收到通知

2.KVO(Key-Value-Observing)机制

  原理图如下:

如图所示:

该机制下观察者的注册是在被观察者的内部进行的,不同于通知机制(由观察者自己注册),需要被观察者和观察者同时实现一个协议:NSKeyValueObserving,被观察者通过addObserver:forKeypath:options:context方法注册观察者,以及要被观察的属性。

上一篇 下一篇

猜你喜欢

热点阅读