Re: Is it possible to traverse dictionaries and arrays using KVC?
Re: Is it possible to traverse dictionaries and arrays using KVC?
- Subject: Re: Is it possible to traverse dictionaries and arrays using KVC?
- From: Thorsten Hohage <email@hidden>
- Date: Tue, 16 Aug 2011 22:49:26 +0200
Hi,
On Tue, 16 Aug 2011 11:03:30 -0700, Tito Ciuro <email@hidden> wrote:
> In KVC, the setValue:forKeyPath: method is super handy to set values in deep hierarchies. I was wondering if it would be possible to access array elements using KVC. I haven't seen any reference about it in the docs, so I was wondering if it's at all possible. Example:
Yes, it is super handy, but as far as I searched there was no way at least until 10.6.x … there might be changes in 10.7, but I didn't know
> Traversing it manually isn't a problem, but if KVC can do it for me, then great!
In my SuperClass all classes needed this (and many, many more) I implemented (but probably not highly optimized!)
- (id)valueForUndefinedKey:(NSString *)key
{
if ([key rangeOfString:@"#"].location != NSNotFound) {
// hack for using array operators in binding!
NSArray *keyArray = [key componentsSeparatedByString:@"#"];
NSString *arrayKey = [keyArray objectAtIndex:0];
NSString *pathKey = [keyArray objectAtIndex:1];
arrayKey = [arrayKey stringByReplacingOccurrencesOfString:@"#" withString:@""];
pathKey = [pathKey stringByReplacingOccurrencesOfString:@":" withString:@"."];
pathKey = [@"@" stringByAppendingString:pathKey];
NSArray *resultList = [self valueForKey:arrayKey];
id result = [resultList valueForKeyPath:pathKey];
return result;
}
if ([key rangeOfString:@"_"].location != NSNotFound) {
// hack for using a "objectAtIndex" notation in KVC
NSArray *keyArray = [key componentsSeparatedByString:@"_"];
NSString *arrayKey = [keyArray objectAtIndex:0];
NSString *indexKey = [keyArray objectAtIndex:1];
NSArray *resultList = [self valueForKey:arrayKey];
if ([resultList count] <= [indexKey intValue])
return nil;
id result = [resultList objectAtIndex:[indexKey intValue]];
return result;
}
…..
}
The first ones allow
positions.#sum.internalCostNettoTotals
AFAIR I choose the "#" instead of "@" due to some parsing issues
The second allow me something like
producer_0.area_0.vineyards_2.idname
regards
Thorsten Hohage
--
objectmanufactur.com - Hamburg,Germany
_______________________________________________
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