Mac Developer Library

Developer

Foundation Framework Reference NSKeyValueObserving Protocol Reference

Options
Deployment Target:

On This Page
Language:

NSKeyValueObserving

Inheritance


Not Applicable

Conforms To


Not Applicable

Import Statement


Swift

import Foundation

Objective-C

@import Foundation;

Availability


Available in OS X v10.3 and later.

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.

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

    Declaration

    Swift

    func observeValueForKeyPath(_ keyPath: String, ofObject object: AnyObject, change change: [NSObject : AnyObject], context context: UnsafeMutablePointer<Void>)

    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.

    Import Statement

    Objective-C

    @import Foundation;

    Swift

    import Foundation

    Availability

    Available in OS X v10.3 and later.

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

    Declaration

    Swift

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

    Objective-C

    + (BOOL)automaticallyNotifiesObserversForKey:(NSString *)key

    Return Value

    YEStrue 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 NOfalse.

    Discussion

    The default implementation returns YEStrue. 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<Key>, and returns the result of invoking that method if it is found. Any found methods must return BOOL. If no such method is found YEStrue is returned.

    Import Statement

    Objective-C

    @import Foundation;

    Swift

    import Foundation

    Availability

    Available in OS X v10.3 and later.

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

    Declaration

    Swift

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

    Objective-C

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

    Parameters

    key

    The key whose value is affected by the key paths.

    Return Value

    Discussion

    When 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<Key>, 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).

    Import Statement

    Objective-C

    @import Foundation;

    Swift

    import Foundation

    Availability

    Available in OS X v10.5 and later.

  • Configures the receiver to post change notifications for a given property if any of the properties specified in a given array changes.

    Deprecation Statement

    You should use the method keyPathsForValuesAffectingValueForKey: instead.

    Declaration

    Objective-C

    + (void)setKeys:(NSArray *)keys triggerChangeNotificationsForDependentKey:(NSString *)dependentKey

    Parameters

    keys

    The names of the properties upon which the value of the property identified by dependentKey depends.

    dependentKey

    The name of a property whose value depends on the properties specified by keys.

    Discussion

    Invocations of will- and did-change KVO notification methods for any key in keys will automatically invoke the corresponding change notification methods for dependentKey. The receiver will not receive willChange/didChange messages to generate the notifications.

    Dependencies should be registered before any instances of the receiving class are created, so you typically invoke this method in a class's initialize method, as illustrated in the following example.

    • + (void)initialize
    • {
    • [self setKeys:[NSArray arrayWithObjects:@"firstName", @"lastName", nil]
    • triggerChangeNotificationsForDependentKey:@"fullName"];
    • }

    Import Statement

    Objective-C

    @import Foundation;

    Availability

    Deprecated in OS X v10.5 and later.

  • Sets the observation info for the receiver.

    Declaration

    Swift

    var observationInfo: UnsafeMutablePointer<Void>

    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.

    Import Statement

    Objective-C

    @import Foundation;

    Swift

    import Foundation

    Availability

    Available in OS X v10.3 and later.

  • Returns a pointer that identifies information about all of the observers that are registered with the receiver.

    Declaration

    Swift

    var observationInfo: UnsafeMutablePointer<Void>

    Objective-C

    @property void *observationInfo

    Return Value

    A pointer that identifies information about all of the observers that are registered with the receiver, the options that were used at registration-time, and so on.

    Discussion

    The default implementation of this method retrieves the information from a global dictionary keyed by the receiver’s pointers.

    For improved performance, this method and setObservationInfo: can be overridden to store the opaque data pointer in an instance variable. Overrides of this method must not attempt to send Objective-C messages to the stored data, including retain and release.

    Import Statement

    Objective-C

    @import Foundation;

    Swift

    import Foundation

    Availability

    Available in OS X v10.3 and later.

  • These constants are returned as the value for a NSKeyValueChangeKindKey key in the change dictionary passed to observeValueForKeyPath:ofObject:change:context: indicating the type of change made:

    Declaration

    Swift

    enum NSKeyValueChange : UInt { case Setting case Insertion case Removal case Replacement }

    Objective-C

    enum { NSKeyValueChangeSetting = 1, NSKeyValueChangeInsertion = 2, NSKeyValueChangeRemoval = 3, NSKeyValueChangeReplacement = 4 }; typedef NSUInteger NSKeyValueChange;

    Constants

    • Setting

      NSKeyValueChangeSetting

      Indicates that the value of the observed key path was set to a new value. This change can occur when observing an attribute of an object, as well as properties that specify to-one and to-many relationships.

      Available in OS X v10.3 and later.

    • Insertion

      NSKeyValueChangeInsertion

      Indicates that an object has been inserted into the to-many relationship that is being observed.

      Available in OS X v10.3 and later.

    • Removal

      NSKeyValueChangeRemoval

      Indicates that an object has been removed from the to-many relationship that is being observed.

      Available in OS X v10.3 and later.

    • Replacement

      NSKeyValueChangeReplacement

      Indicates that an object has been replaced in the to-many relationship that is being observed.

      Available in OS X v10.3 and later.

    Import Statement

    Objective-C

    @import Foundation;

    Swift

    import Foundation

    Availability

    Available in OS X v10.3 and later.

  • These constants are passed to addObserver:forKeyPath:options:context: and determine the values that are returned as part of the change dictionary passed to an observeValueForKeyPath:ofObject:change:context:. You can pass 0 if you require no change dictionary values.

    Declaration

    Swift

    struct NSKeyValueObservingOptions : RawOptionSetType { init(_ rawValue: UInt) init(rawValue rawValue: UInt) static var New: NSKeyValueObservingOptions { get } static var Old: NSKeyValueObservingOptions { get } static var Initial: NSKeyValueObservingOptions { get } static var Prior: NSKeyValueObservingOptions { get } }

    Objective-C

    enum { NSKeyValueObservingOptionNew = 0x01, NSKeyValueObservingOptionOld = 0x02, NSKeyValueObservingOptionInitial = 0x04, NSKeyValueObservingOptionPrior = 0x08 }; typedef NSUInteger NSKeyValueObservingOptions;

    Constants

    • New

      NSKeyValueObservingOptionNew

      Indicates that the change dictionary should provide the new attribute value, if applicable.

      Available in OS X v10.3 and later.

    • Old

      NSKeyValueObservingOptionOld

      Indicates that the change dictionary should contain the old attribute value, if applicable.

      Available in OS X v10.3 and later.

    • Initial

      NSKeyValueObservingOptionInitial

      If specified, a notification should be sent to the observer immediately, before the observer registration method even returns.

      The change dictionary in the notification will always contain an NSKeyValueChangeNewKey entry if NSKeyValueObservingOptionNew is also specified but will never contain an NSKeyValueChangeOldKey entry. (In an initial notification the current value of the observed property may be old, but it's new to the observer.) You can use this option instead of explicitly invoking, at the same time, code that is also invoked by the observer's observeValueForKeyPath:ofObject:change:context: method. When this option is used withaddObserver:forKeyPath:options:context: a notification will be sent for each indexed object to which the observer is being added.

      Available in OS X v10.5 and later.

    • Prior

      NSKeyValueObservingOptionPrior

      Whether separate notifications should be sent to the observer before and after each change, instead of a single notification after the change.

      The change dictionary in a notification sent before a change always contains an NSKeyValueChangeNotificationIsPriorKey entry whose value is [NSNumber numberWithBool:YES], but never contains an NSKeyValueChangeNewKey entry. When this option is specified the change dictionary in a notification sent after a change contains the same entries that it would contain if this option were not specified. You can use this option when the observer's own key-value observing-compliance requires it to invoke one of the -willChange... methods for one of its own properties, and the value of that property depends on the value of the observed object's property. (In that situation it's too late to easily invoke -willChange... properly in response to receiving an observeValueForKeyPath:ofObject:change:context: message after the change.)

      Available in OS X v10.5 and later.

    Import Statement

    Objective-C

    @import Foundation;

    Swift

    import Foundation

    Availability

    Available in OS X v10.3 and later.

  • These constants are used as keys in the change dictionary passed to observeValueForKeyPath:ofObject:change:context:.

    Declaration

    Swift

    let NSKeyValueChangeKindKey: String let NSKeyValueChangeNewKey: String let NSKeyValueChangeOldKey: String let NSKeyValueChangeIndexesKey: String let NSKeyValueChangeNotificationIsPriorKey: String

    Objective-C

    NSString *const NSKeyValueChangeKindKey; NSString *const NSKeyValueChangeNewKey; NSString *const NSKeyValueChangeOldKey; NSString *const NSKeyValueChangeIndexesKey; NSString *const NSKeyValueChangeNotificationIsPriorKey;

    Constants

    • NSKeyValueChangeKindKey

      NSKeyValueChangeKindKey

      An NSNumber object that contains a value corresponding to one of the NSKeyValueChange enums, indicating what sort of change has occurred.

      A value of NSKeyValueChangeSetting indicates that the observed object has received a setValue:forKey: message, or that the key-value-coding-compliant set method for the key has been invoked, or that one of the willChangeValueForKey: or didChangeValueForKey: methods has otherwise been invoked.

      A value of NSKeyValueChangeInsertion, NSKeyValueChangeRemoval, or NSKeyValueChangeReplacement indicates that mutating messages have been sent a key-value observing compliant collection proxy, or that one of the key-value-coding-compliant collection mutation methods for the key has been invoked, or a collection will change or did change method has been otherwise been invoked.

      You can use NSNumber's intValue method to retrieve the integer value of the change kind.

      Available in OS X v10.3 and later.

    • NSKeyValueChangeNewKey

      NSKeyValueChangeNewKey

      If the value of the NSKeyValueChangeKindKey entry is NSKeyValueChangeSetting, and NSKeyValueObservingOptionNew was specified when the observer was registered, the value of this key is the new value for the attribute.

      For NSKeyValueChangeInsertion or NSKeyValueChangeReplacement, if NSKeyValueObservingOptionNew was specified when the observer was registered, the value for this key is an NSArray instance that contains the objects that have been inserted or replaced other objects, respectively.

      Available in OS X v10.3 and later.

    • NSKeyValueChangeOldKey

      NSKeyValueChangeOldKey

      If the value of the NSKeyValueChangeKindKey entry is NSKeyValueChangeSetting, and NSKeyValueObservingOptionOld was specified when the observer was registered, the value of this key is the value before the attribute was changed.

      For NSKeyValueChangeRemoval or NSKeyValueChangeReplacement, if NSKeyValueObservingOptionOld was specified when the observer was registered, the value is an NSArray instance that contains the objects that have been removed or have been replaced by other objects, respectively.

      Available in OS X v10.3 and later.

    • NSKeyValueChangeIndexesKey

      NSKeyValueChangeIndexesKey

      If the value of the NSKeyValueChangeKindKey entry is NSKeyValueChangeInsertion, NSKeyValueChangeRemoval, or NSKeyValueChangeReplacement, the value of this key is an NSIndexSet object that contains the indexes of the inserted, removed, or replaced objects.

      Available in OS X v10.3 and later.

    • NSKeyValueChangeNotificationIsPriorKey

      NSKeyValueChangeNotificationIsPriorKey

      If the option NSKeyValueObservingOptionPrior was specified when the observer was registered this notification is sent prior to a change.

      The change dictionary contains an NSKeyValueChangeNotificationIsPriorKey entry whose value is an NSNumber wrapping YEStrue.

      Available in OS X v10.5 and later.

  • These constants are specified as the parameter to the methods willChangeValueForKey:withSetMutation:usingObjects: and didChangeValueForKey:withSetMutation:usingObjects:. Their semantics correspond exactly to the NSMutableSet class methods unionSet:, minusSet:, intersectSet:, and setSet: method, respectively.

    Declaration

    Swift

    enum NSKeyValueSetMutationKind : UInt { case UnionSetMutation case MinusSetMutation case IntersectSetMutation case SetSetMutation }

    Objective-C

    enum { NSKeyValueUnionSetMutation = 1, NSKeyValueMinusSetMutation = 2, NSKeyValueIntersectSetMutation = 3, NSKeyValueSetSetMutation = 4 }; typedef NSUInteger NSKeyValueSetMutationKind;

    Constants

    • UnionSetMutation

      NSKeyValueUnionSetMutation

      Indicates that objects in the specified set are being added to the receiver.

      This mutation kind results in a NSkeyValueChangeKindKey value of NSKeyValueChangeInsertion.

      Available in OS X v10.4 and later.

    • MinusSetMutation

      NSKeyValueMinusSetMutation

      Indicates that the objects in the specified set are being removed from the receiver.

      This mutation kind results in a NSkeyValueChangeKindKey value of NSKeyValueChangeRemoval.

      Available in OS X v10.4 and later.

    • IntersectSetMutation

      NSKeyValueIntersectSetMutation

      Indicates that the objects not in the specified set are being removed from the receiver.

      This mutation kind results in a NSkeyValueChangeKindKey value of NSKeyValueChangeRemoval.

      Available in OS X v10.4 and later.

    • SetSetMutation

      NSKeyValueSetSetMutation

      Indicates that set of objects are replacing the existing objects in the receiver.

      This mutation kind results in a NSKeyValueChangeKindKey value of NSKeyValueChangeReplacement.

      Available in OS X v10.4 and later.

    Import Statement

    Objective-C

    @import Foundation;

    Swift

    import Foundation

    Availability

    Available in OS X v10.4 and later.