代理delegate、NSNotification、KVC、KVO的區別

代理

蘋果的官方文檔解釋:程序員

Delegation is a simple and powerful pattern in which one object in a 
program acts on behalf of, or in coordination with, another object. 
The delegating object keeps a reference to the other object—the 
delegate—and at the appropriate time sends a message to it. The 
message informs the delegate of an event that the delegating object is 
about to handle or has just handled. The delegate may respond to the 
message by updating the appearance or state of itself or other objects 
in the application, and in some cases it can return a value that 
affects how an impending event is handled. The main value of 
delegation is that it allows you to easily customize the behavior of 
several objects in one central object.設計模式

代理或者委託實質上是一種設計模式中的代理模式,是對象之間傳遞信息的一種方式,這種模式用於一個對象「表明」另一個對象和程序中其餘的對象進行交互。這是一種一對一的關係,delegate的接收者能夠向這個對象返回消息。app

簡單的說,把一個類本身須要作的一部分事情,讓另外一個類(也能夠就是本身自己)來完成。框架

NSNotification

NSNotification objects encapsulate information so that it can be 
broadcast to other objects by an NSNotificationCenter object. An 
NSNotification object (referred to as a notification) contains a name, 
an object, and an optional dictionary. The name is a tag identifying 
the notification. The object is any object that the poster of the 
notification wants to send to observers of that notification 
(typically, it is the object that posted the notification). The 
dictionary stores other related objects, if any. NSNotification 
objects are immutable objects.ide

消息中心實質是設計模式中的觀察者模式,是一種一對多的關係,消息發送者只負責發送消息,不能接收消息。函數

關於delegate的用法能夠參照 
http://blog.csdn.net/lovefqing/article/details/8270111] 
NSNotification的用法能夠參照 
http://blog.csdn.net/dqjyong/article/details/7678108post

KVC

KVC是KeyValueCoding的簡稱,它是一種能夠直接經過字符串的名字(key)來訪問類屬性的機制。而不是經過調用Setter、Getter方法訪問。.net

關鍵方法定義在:NSKeyValueCodingprotocol設計

KVC支持類對象和內建基本數據類型。代理

獲取值

valueForKey:,傳入NSString屬性的名字。

valueForKeyPath:,傳入NSString屬性的路徑,xx.xx形式。

valueForUndefinedKey它的默認實現是拋出異常,能夠重寫這個函數作錯誤處理。

修改值

setValue:forKey:

setValue:forKeyPath:

setValue:forUndefinedKey:

setNilValueForKey:當對非類對象屬性設置nil時,調用,默認拋出異常。

一對多關係成員的狀況

mutableArrayValueForKey:有序一對多關係成員 NSArray

mutableSetValueForKey:無序一對多關係成員 NSSet

KVO

KVO,即:Key-Value Observing,它提供一種機制,當指定的對象的屬性被修改後,則對象就會接受到通知。簡單的說就是每次指定的被觀察的對象的屬性被修改後,KVO就會自動通知相應的觀察者了。

使用方法 
系統框架已經支持KVO,因此程序員在使用的時候很是簡單。 
1. 註冊,指定被觀察者的屬性, 
2. 實現回調方法 
3. 移除觀察

總結

以個人理解,其實NSNotification\kvc\kvo都是運用了設計模式中的觀察者模式(監聽模式), delegate是設計模式中的委託模式。

NSNotification的對象很簡單,就是poster要提供給observer的信息包裹。

KVC是一種間接訪問對象屬性的機制,而不是直接經過設置器和訪問器或者點語法來訪問對象屬性。

KVO當對象的某一個屬性發生變化的時候,獲得一個相應的通知。

觀察者模式適用於一些數據發生變化,引起UIView變化的場景。

相關文章
相關標籤/搜索