代理

苹果的官方文档解释:

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的接收者可以向这个对象返回消息。

简单的说,把一个类自己需要做的一部分事情,让另一个类(也可以就是自己本身)来完成。

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.

消息中心实质是设计模式中的观察者模式,是一种一对多的关系,消息发送者只负责发送消息,不能接收消息。

关于delegate的用法可以参照 
http://blog.csdn.net/lovefqing/article/details/8270111] 
NSNotification的用法可以参照 
http://blog.csdn.net/dqjyong/article/details/7678108

KVC

KVC是KeyValueCoding的简称,它是一种可以直接通过字符串的名字(key)来访问类属性的机制。而不是通过调用Setter、Getter方法访问。

关键方法定义在: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变化的场景。

posted on 2015-04-06 15:40  Jelly_L  阅读(486)  评论(0编辑  收藏  举报