KVO---NSKeyValueObserving

The NSKeyValueObserving (KVO) informal protocol[非正式协议] defines a mechanism(机制) that allows objects to be notified of changes to the specified properties of other objects.

You can observe any object properties including simple attributes, to-one relationships, and to-many relationships. Observers of to-many relationships are informed of the type of change made — as well as which objects are involved in the change.

NSObject provides an implementation of the NSKeyValueObserving protocol that provides an automatic observing capability for all objects. You can further refine notifications by disabling automatic observer notifications and implementing manual notifications using the methods in this protocol.

NOTE----Key-value observing is not available for Java applications.

Change notification

- observeValueForKeyPath:ofObject:change:context:

This message is sent to the receiver when the value at the specified key path relative to the given object has changed.

DeclarationSWIFT

func observeValueForKeyPath(_ keyPath: String?,                

                        ofObject object: AnyObject?,  

                        change change: [String : AnyObject]?,      

                     context context: UnsafeMutablePointer)

OBJECTIVE-C

- (void)observeValueForKeyPath:(NSString *)keyPath        

                                    ofObject:(id)object

                                      change:(NSDictionary*)change

                                        context:(void *)context

Parameters

keyPath   The key path, relative to object, to the value that has changed.

object     The source object of the key path keyPath.

change   A dictionary that describes the changes that have been made to the value of the property at the key path keyPath relative to object. Entries are described in Change Dictionary Keys.

context   The value that was provided when the receiver was registered to receive key-value observation notifications.

Discussion

The receiver must be registered as an observer for the specified keyPath and object.


Registering for observation

- addObserver:forKeyPath:options:context:

Registers anObserver to receive KVO notifications for the specified key-path relative to the receiver.

DeclarationSWIFT

func addObserver(_ observer: NSObject,

              forKeyPath keyPath: String,  

                   options options: NSKeyValueObservingOptions,  

                   context context: UnsafeMutablePointer)

OBJECTIVE-C

- (void)addObserver:(NSObject *)anObserver

              forKeyPath:(NSString *)keyPath

                   options:(NSKeyValueObservingOptions)options

                   context:(void *)context

Parameters

anObserver    The object to register for KVO notifications. The observer must implement the key-value observing method observeValueForKeyPath:ofObject:change:context:.

keyPath The key path, relative to the receiver, of the property to observe. This value must not be nil.

options  A combination of the NSKeyValueObservingOptions values that specifies what is included in observation notifications. For possible values, see NSKeyValueObservingOptions.

context  Arbitrary data that is passed to anObserver in observeValueForKeyPath:ofObject:change:context:.

Discussion

Neither the receiver, nor anObserver, are retained. An object that calls this method must also call either the removeObserver:forKeyPath: or removeObserver:forKeyPath:context: method when participating in KVO.

- removeObserver:forKeyPath:

Stops a given object from receiving change notifications for the property specified by a given key-path relative to the receiver.

Declaration

SWIFT

func removeObserver(_ observer: NSObject,

                    forKeyPath keyPath: String)

OBJECTIVE-C

- (void)removeObserver:(NSObject *)anObserver

                   forKeyPath:(NSString *)keyPath

Parameters

anObserver   The object to remove as an observer.

keyPath     A key-path, relative to the receiver, for which anObserver is registered to receive KVO change notifications.

Discussion

It is an error to call removeObserver:forKeyPath: if the object has not been registered as an observer.

Be sure to invoke this method (or removeObserver:forKeyPath:context:) before any object specified in addObserver:forKeyPath:options:context: is deallocated.


- removeObserver:forKeyPath:context:

Stops a given object from receiving change notifications for the property specified by a given key-path relative to the receiver and a context.

DeclarationSWIFT

func removeObserver(_ observer: NSObject,

                    forKeyPath keyPath: String,

                         context context: UnsafeMutablePointer)

OBJECTIVE-C

- (void)removeObserver:(NSObject *)observer

                    forKeyPath:(NSString *)keyPath

                        context:(void *)context

Parameters

observer     The object to remove as an observer.

keyPath      A key-path, relative to the receiver, for which anObserver is registered to receive KVO change notifications.

context     Arbitrary data that more specifically identifies the observer to be removed.

Discussion

Examining the value in context you are able to determine precisely which addObserver:forKeyPath:options:context: invocation was used to create the observation relationship(观察关系,监听关系). When the same observer is registered for the same key-path multiple times, but with different context pointers, an application can determine specifically which object to stop observing. It is an error to call removeObserver:forKeyPath:context: if the object has not been registered as an observer.

Be sure to invoke this method (or removeObserver:forKeyPath:) before any object specified in addObserver:forKeyPath:options:context: is deallocated.


Notifying observers of changes(通知 观察者 的变化)

- willChangeValueForKey:

Invoked(唤起) to inform(通知) the receiver that the value of a given property is about to change.

Declaration

SWIFT

func willChangeValueForKey(_ key: String)

OBJECTIVE-C

- (void)willChangeValueForKey:(NSString *)key

Parameters

key   The name of the property that will change.

Discussion

You should invoke this method when implementing key-value observer compliance manually.

The change type of this method is NSKeyValueChangeSetting.

IMPORTANT

After the values have been changed, a corresponding didChangeValueForKey: must be invoked with the same parameter.

Special Considerations

You should not override this method in subclasses.


See Also

– didChangeValueForKey:

– willChange:valuesAtIndexes:forKey:

- didChangeValueForKey:

Invoked to inform the receiver that the value of a given property has changed.

Declaration

SWIFT

func didChangeValueForKey(_ key: String)

OBJECTIVE-C

- (void)didChangeValueForKey:(NSString *)key

Parameters

key     The name of the property that changed.

Discussion

You should invoke this method when implementing key-value observer compliance manually.

Special Considerations

You should not override this method in subclasses.

See Also

– willChangeValueForKey:

– didChange:valuesAtIndexes:forKey:

- willChange:valuesAtIndexes:forKey:

Invoked to inform the receiver that the specified change is about to be executed at given indexes for a specified ordered to-many relationship.

Declaration

SWIFT

func willChange(_ changeKind: NSKeyValueChange,

        valuesAtIndexes indexes: NSIndexSet,

                             forKey key: String)

OBJECTIVE-C

- (void)willChange:(NSKeyValueChange)change

   valuesAtIndexes:(NSIndexSet *)indexes

                  forKey:(NSString *)key

Parameters

change    The type of change that is about to be made.

indexes     The indexes of the to-many relationship that will be affected by the change.

key    The name of a property that is an ordered to-many relationship.

Discussion

You should invoke this method when implementing key-value-observing compliance manually.

IMPORTANT

After the values have been changed, a corresponding didChange:valuesAtIndexes:forKey: must be invoked with the same parameters.

Special Considerations

You should not override this method in subclasses.


See Also

– didChange:valuesAtIndexes:forKey:

– willChangeValueForKey:

- didChange:valuesAtIndexes:forKey:

Invoked to inform the receiver that the specified change has occurred on the indexes for a specified ordered to-many relationship.

Declaration

SWIFT

func didChange(_ changeKind: NSKeyValueChange,

       valuesAtIndexes indexes: NSIndexSet,

                             forKey key: String)

OBJECTIVE-C

- (void)didChange:(NSKeyValueChange)change

   valuesAtIndexes:(NSIndexSet *)indexes

                  forKey:(NSString *)key

Parameters

change     The type of change that was made.

indexes    The indexes of the to-many relationship that were affected by the change.

key   The name of a property that is an ordered to-many relationship.

Discussion

You should invoke this method when implementing key-value-observing compliance manually.

Special Considerations

You should not override this method in subclasses.


See Also

– willChange:valuesAtIndexes:forKey:

– didChangeValueForKey:

- willChangeValueForKey:withSetMutation:usingObjects:

Invoked to inform the receiver that the specified change is about to be made to a specified unordered to-many relationship.

DeclarationSWIFT

func willChangeValueForKey(_ key: String,

      withSetMutation mutationKind: NSKeyValueSetMutationKind,                                usingObjects objects: Set)

OBJECTIVE-C

- (void)willChangeValueForKey:(NSString *)key

                      withSetMutation:(NSKeyValueSetMutationKind)mutationKind

                          usingObjects:(NSSet *)objects

Parameters

key    The name of a property that is an unordered to-many relationship

mutationKind     The type of change that will be made.

objects    The objects that are involved in the change (see NSKeyValueSetMutationKind).

Discussion

You invoke this method when implementing key-value observer compliance manually.

IMPORTANT

After the values have been changed, a corresponding didChangeValueForKey:withSetMutation:usingObjects: must be invoked with the same parameters.

Special Considerations

You should not override this method in subclasses.

See Also

– didChangeValueForKey:withSetMutation:usingObjects:

- didChangeValueForKey:withSetMutation:usingObjects:

Invoked to inform the receiver that the specified change was made to a specified unordered to-many relationship.

DeclarationSWIFT

func didChangeValueForKey(_ key: String,        

     withSetMutation mutationKind: NSKeyValueSetMutationKind,                             usingObjects objects: Set)

OBJECTIVE-C

- (void)didChangeValueForKey:(NSString *)key

                     withSetMutation:(NSKeyValueSetMutationKind)mutationKind

                         usingObjects:(NSSet *)objects

Parameters

key    The name of a property that is an unordered to-many relationship

mutationKind    The type of change that was made.

objects   The objects that were involved in the change (see NSKeyValueSetMutationKind).

Discussion

You invoke this method when implementing key-value observer compliance manually.

Special Considerations

You should not override this method in subclasses.


Observing customization----自定义观察机制

+ automaticallyNotifiesObserversForKey:

Returns a Boolean value that indicates whether the receiver supports automatic key-value observation for the given key.

DeclarationSWIFT

class func automaticallyNotifiesObserversForKey(_ key: String) -> Bool

OBJECTIVE-C

+ (BOOL)automaticallyNotifiesObserversForKey:(NSString *)keyReturn ValueYES if the key-value observing machinery should automatically invoke willChangeValueForKey:/didChangeValueForKey: and willChange:valuesAtIndexes:forKey:/didChange:valuesAtIndexes:forKey: whenever instances of the class receive key-value coding messages for the key, or mutating key-value-coding-compliant methods for the key are invoked; otherwise NO.

Discussion

The default implementation returns YES. Starting in OS X 10.5, the default implementation of this method searches the receiving class for a method whose name matches the pattern

+automaticallyNotifiesObserversOf, and returns the result of invoking that method if it is found. Any found methods must return BOOL. If no such method is found YES is returned.

+ keyPathsForValuesAffectingValueForKey:

Returns a set of key paths for properties whose values affect the value of the specified key.

DeclarationSWIFT

class func keyPathsForValuesAffectingValueForKey(_ key: String) -> Set

OBJECTIVE-C

+ (NSSet*)keyPathsForValuesAffectingValueForKey:(NSString *)keyParameterskey

The key whose value is affected by the key paths.Return ValueDiscussionWhen an observer for the key is registered with an instance of the receiving class, key-value observing itself automatically observes all of the key paths for the same instance, and sends change notifications for the key to the observer when the value for any of those key paths changes.The default implementation of this method searches the receiving class for a method whose name matches the pattern +keyPathsForValuesAffecting, and returns the result of invoking that method if it is found. Any such method must return an NSSet. If no such method is found, an NSSet that is computed from information provided by previous invocations of the now-deprecated setKeys:triggerChangeNotificationsForDependentKey: method is returned, for backward binary compatibility.You can override this method when the getter method of one of your properties computes a value to return using the values of other properties, including those that are located by key paths. Your override should typically invoke super and return a set that includes any members in the set that result from doing that (so as not to interfere with overrides of this method in superclasses).

NOTE

You must not override this method when you add a computed property to an existing class using a category, overriding methods in categories is unsupported. In that case, implement a matching +keyPathsForValuesAffectingto take advantage of this mechanism.

Availability

Available in iOS 2.0 and later.

- observationInfo

Sets the observation info for the receiver.

DeclarationSWIFT

var observationInfo: UnsafeMutablePointer

OBJECTIVE-C

@property void *observationInfo

Parameters

observationInfo    The observation info for the receiver.

Discussion

The observationInfo is a pointer that identifies information about all of the observers that are registered with the receiver. The default implementation of this method stores observationInfo in a global dictionary keyed by the receiver’s pointers.

For improved performance, this method and observationInfo can be overridden to store the opaque data pointer in an instance variable. Classes that override this method must not attempt to send Objective-C messages to observationInfo, including retain and release.

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 203,271评论 5 476
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 85,275评论 2 380
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 150,151评论 0 336
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,550评论 1 273
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,553评论 5 365
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,559评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,924评论 3 395
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,580评论 0 257
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,826评论 1 297
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,578评论 2 320
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,661评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,363评论 4 318
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,940评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,926评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,156评论 1 259
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,872评论 2 349
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,391评论 2 342

推荐阅读更多精彩内容

  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 9,355评论 0 23
  • 1. 描述网页从打开到显示的过程 解析:前端原理问题。 解析 HTML 文档生成DOM树,解析CSS文件生成CSS...
    jdzhangxin阅读 219评论 0 1
  • 今天的内心压抑,近期被太多事情压抑着,导致自己处于绷紧,烦躁的状态!一直在想着该如何更好地与客户合作,更顺利地完成...
    Tristaye阅读 249评论 0 0
  • 如果不是一场意外,他认为他和她会牵手到老,从大学到相识相恋,到一起生活,他们已经走过了二十个春秋。人的一生最美好的...
    米小米米阅读 385评论 1 2