How to Transfer Data Via KVO Notifications?
so I am able to successfully have another class of mine be notified via KVO notification when a class instance value changes, but I have no idea of how I would go about transferring data between the two objects. I am aware that it is possible to do such things via t开发者_如何学Che context:
parameter, however Apple's documentation fails to indicate how to go about doing that.
I am aware that you place a pointer to an object as the context parameter in the addObserver:forKeyPath:options:context:
message, but how does the object that is being observed "see" that object that is pointed to so it can make modifications accordingly?
Thanks!
The context argument is not meant as a data-transfer device, it just helps the observing class to distinguish different observations from each other. I’m not sure if you understand KVO right. KVO is used when you want to know about updates to a certain property. Upon receiving the notification you usually do something with the old/new property value:
- (void) observeValueForKeyPath: (NSString*) keyPath ofObject: (id) sender
change: (NSDictionary*) change context: (void*) context
{
id newValue = [change objectForKey:NSKeyValueChangeNewKey];
NSLog(@"New property value: %@.", newValue);
}
In this use case it does not make much sense to talk about “transferring data” between the two parties. If you want to get some extra data in addition to the property changes, you can easily expose that data as a property on the class being observed. Or forget about KVO and trigger a regular NSNotification
with all the required data passed as the user info object:
NSDictionary *info = [NSDictionary dictionaryWithObjectsAndKeys:
foo, @"foo", bar, @"bar", nil];
[[NSNotificationCenter defaultCenter] postNotificationName:@"Foo"
object:self userInfo:info];
So I got it working like so...
I have an object (obj A) that needs to observe another object (obj B) and implements the following function: observeValueForKeyPath:ofObject:change:context:
Obj B calls the following in its init function:
[self addObserver:[<some singleton class> sharedManager] forKeyPath:@"someVar" options:(NSKeyValueObservingOptionNew) context:self];
Of course the observer class does not need to be a singleton class, but of course it is very convenient. I passed in the object being observed as the context and that allowed obj A to access all ivars for obj B in the observeValueForKeyPath:ofObject:change:context:
function.
As I discovered, different background threads aren't used for KVO notifications, so I am reverting back to using protocols to transfer information as they both work out the same.
This form of data transfer is not recommended, but I wanted to just point out that it is indeed possible.
精彩评论