Re: Detecting reading a key in KVC
Re: Detecting reading a key in KVC
- Subject: Re: Detecting reading a key in KVC
- From: Quincey Morris <email@hidden>
- Date: Fri, 12 Nov 2010 10:16:46 -0800
On Nov 12, 2010, at 01:45, Remco Poelstra wrote:
> @interface PropertiesController: NSObject {
> NSMutableDictionary *properties;
> }
>
> -valueForKey:
> -setValue:forKey:
> @end
> @implementation PropertiesController
> valueForKey {
> id retVal=[properties valueForKey:key];
> if (!retVal) {
> //fetch value from network
> //We do not wait for the value
> }
> return retVal;
> }
> @end
> If I ommit the valueForKey method, how does the KVC logic now, that it should check the properties variable?
> Further more, NSDictionary seems to always return a value, so all keys are "defined", they just return nil sometimes. How can valueForUndefinedKey: then ever be called?
As as been said several times in this thread, you *shouldn't* override 'valueForKey:', but instead override 'valueForUndefinedKey:' like this:
@implementation PropertiesController
- (id) valueForUndefinedKey: (NSString*) key {
id retVal=[properties objectForKey:key]; // note: NOT 'valueForKey:'
if (!retVal) {
//fetch value from network
//We do not wait for the value
}
return retVal;
}
@end
If you want to know how control reaches this method, read the documentation:
http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/KeyValueCoding/Concepts/SearchImplementation.html#//apple_ref/doc/uid/20000955-CJBBBFFA
The only restriction here is that none of your dictionary keys should be the same as existing NSObject property names, because KVC references to those keys will go to the existing methods instead of 'valueForUndefinedKey:'. For example, a dictionary key "class" isn't going to work. If there's a chance the dictionary keys will conflict with NSObject property names, you are going to have to take steps to ensure the keys are made unique.
_______________________________________________
Cocoa-dev mailing list (email@hidden)
Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden