Tuesday, June 3, 2014

Key-Value Observations in ObjC



// MyClass1.h:
    @interface MyClass1 : NSObject
    @property (nonatomic, copy) NSString* value;
    @end
    // MyClass2.m:
    - (void) observeValueForKeyPath:(NSString *)keyPath
                           ofObject:(id)object
                             change:(NSDictionary *)change
                            context:(void *)context {
        NSLog(@"I heard about the change!");
    }
   
    // Somewhere else entirely:
    MyClass1* objectA = [MyClass1 new];
    MyClass2* objectB = [MyClass2 new];
   
    // register for KVO
    [objectA addObserver:objectB forKeyPath:@"value" options:0 context:nil];
   
    // change the value in a KVO compliant way
    objectA.value = @"Hello, world!";
    // result: objectB's observeValueForKeyPath:... is called
   
--------------------------------------------------------------------

objectA.value = @"Hello";
[objectA addObserver:objectB forKeyPath:@"value" options: NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld
context: nil];
objectA.value = @"Goodbye"; // notification is triggered
   
   
- (void) observeValueForKeyPath:(NSString *)keyPath
                           ofObject:(id)object
                             change:(NSDictionary *)change
                            context:(void *)context {
        id newValue = change[NSKeyValueChangeNewKey];
        id oldValue = change[NSKeyValueChangeOldKey];
        NSLog(@"The key path %@ changed from %@ to %@",
              keyPath, oldValue, newValue);
}

--------------------------------------------------------------------

No comments: