Observing a property of a NSObject subclass

suggest change

Most KVO and KVC functionality is already implemented by default on all NSObject subclasses.

To start observing a property named firstName of an object named personObject do this in the observing class:

[personObject addObserver:self
               forKeyPath:@"firstName"
                  options:NSKeyValueObservingOptionNew
                  context:nil];

The object that self in the above code refers to will then receive a observeValueForKeyPath:ofObject:change:context: message whenever the observed key path changes.

- (void)observeValueForKeyPath:(NSString *)keyPath
                      ofObject:(id)object
                        change:(NSDictionary<NSString *,id> *)change
                       context:(void *)context
{
    NSLog(@"new value of %@ is: %@", keyPath, change[NSKeyValueChangeNewKey]);
}

“Key path” is a KVC term. NSObject subclasses implement KVC functionality by default.

An instance variable named _firstName will be accessible by the @"firstName" key path.

A getter method named firstName will be called when accessing the @"firstName" key path, regardless of there being a _firstName instance variable or setFirstName setter method.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:


Key Value Coding:
* Observing a property of a NSObject subclass

Table Of Contents
12 UIView
15 UIColor
26 UIImage
28 CALayer
30 NSDate
40 iBeacon
49 NSTimer
65 Key Value Coding
79 NSURL
87 AWS SDK
96 NSData
101 Segues
104 EventKit
105 NSBundle
106 SiriKit
111 StoreKit
117 3D Touch
119 Keychain
122 Block
141 AirDrop
144 UISlider
145 Carthage
146 HealthKit
151 plist
157 MVVM
164 UIPhoenix
166 Simulator
168 NSArray
169 OpenGL
175 Core Data
179 MyLayout
180 UIFont
189 Security
200 Codable