How to transfer data through KVO notifications?

therefore, I can successfully notify another class of my notification via KVO when the value of the class instance changes, but I do not know how I will transfer data between two objects. I know that this can be done using a parameter context:, however, the Apple documentation does not indicate how to do this.

I know that you put a pointer to an object as the context parameter in the message addObserver:forKeyPath:options:context:, but how does the observed object “see” this object, which it points to so that it can make the appropriate changes?

Thank!

+3
source share
2 answers

So, I started working like this ...

(obj A), (obj B) : observeValueForKeyPath:ofObject:change:context:

Obj B init :

[self addObserver:[<some singleton class> sharedManager] forKeyPath:@"someVar" options:(NSKeyValueObservingOptionNew) context:self];

, , , , . , , obj A ivars obj B observeValueForKeyPath:ofObject:change:context:.

, KVO , , .

, , .

0

, . , KVO. KVO , . , - / :

- (void) observeValueForKeyPath: (NSString*) keyPath ofObject: (id) sender
    change: (NSDictionary*) change context: (void*) context
{
    id newValue = [change objectForKey:NSKeyValueChangeNewKey];
    NSLog(@"New property value: %@.", newValue);
}

" " . , . KVO NSNotification , :

NSDictionary *info = [NSDictionary dictionaryWithObjectsAndKeys:
    foo, @"foo", bar, @"bar", nil];
[[NSNotificationCenter defaultCenter] postNotificationName:@"Foo"
    object:self userInfo:info];
+1

All Articles