---
title: "NSNotification、delegate和KVO的区别"
author: "lancehan"
date: "2013-11-26T19:37:46Z"
tags: []
categories: ["编程语言"]
slug: "nsnotification-delegate-kvo"
draft: false
lastmod: "2013-11-26T19:37:46Z"
id: 1981125
url: "https://lancehan.iteye.com/blog/1981125"
---

KVO vs NSNotification vs protocol/delegate：  
1\. Use a delegate if you want to talk to only one object. For example, a tableView has a delegate - only one object should be responsible for dealing with it.  
2\. Use notifications if you want to tell everyone that something has happened. For example in low memory situations a notification is sent telling your app that there has been a memory warning. Because lots of objects in your app might want to lower their memory usage it's a notification.  
3\. I don't think KVO is a good idea at all and try not to use it but, if you want to find out if a property has changed you can listen for changes. 

 

1. 效率肯定是delegate比NSNotification高。

delegate方法比notification更加直接，最典型的特征是，delegate方法往往需要关注返回值， 也就是delegate方法的结果。比如-windowShouldClose:，需要关心返回的是yes还是no。所以delegate方法往往包含 should这个很传神的词。也就是好比你做我的delegate，我会问你我想关闭窗口你愿意吗？你需要给我一个答案，我根据你的答案来决定如何做下一 步。相反的，notification最大的特色就是不关心接受者的态度， 我只管把通告放出来，你接受不接受就是你的事情，同时我也不关心结果。所以notification往往用did这个词汇，比如 NSWindowDidResizeNotification，那么NSWindow对象放出这个notification后就什么都不管了也不会等待接 受者的反应。

2、KVO和NSNotification的区别：

和delegate一样，KVO和NSNotification的作用也是类与类之间的通信，与delegate不同的是1）这两个都是负责发出通知，剩下的事情就不管了，所以没有返回值；2）delegate只是一对一，而这两个可以一对多。这两者也有各自的特点。

1）KVO的使用：

被观察者发出  **addObserver:forKeyPath:options:context:**  方法来添加观察者。

然后只要被观察者的keyPath值变化(注意：单纯改变其值不会调用此方法，只有通过getters和setters来改变值才会触发KVO)，就会在观察者里调用方法**observeValueForKeyPath:ofObject:change:context:**

因此观察者需要实现方法 **observeValueForKeyPath:ofObject:change:context:** 来对KVO发出的通知做出响应。

这 些代码都只需在观察者里进行实现，被观察者不用添加任何代码，所以谁要监听谁注册，然后对响应进行处理即可，使得观察者与被观察者完全解耦，运用很灵活很 简便；但是KVO只能检测类中的属性，并且属性名都是通过NSString来查找，编译器不会帮你检错和补全，纯手敲所以比较容易出错。

2）NSNotification的使用

这里的通知不是由被观察者发出，而是由NSNotificationCenter来统一发出，而不同通知通过唯一的通知标识名notificationName来区分，标识名由发送通知的类来起。

首先被观察者自己在必要的方法A里，通过方法**postNotificationName:object:**来发出通知notificationName这样发送通知者这边的工作就完成了，每次A被调用，就会发送一次通知notificationName。

然后谁要监听A的变化，就通过**\[NSNotificationCenter defaultCenter]**的方法**addObserver:selector:name:object:**为观察者注册监听name为notificationName的通知然后每次发出name为notificationName的通知时，注册监听后的观察者就会调用其自己定义的方法notificationSelector来进行响应。

NSNotification的特点呢，就是需要被观察者先主动发出通知，然后观察者注册监听后再来进行响应，比KVO多了发送通知的一步，但是其优点是监听不局限于属性的变化，还可以对多种多样的状态变化进行监听，监听范围广，使用也更灵活。