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: Andy Lee <email@hidden>
- Date: Tue, 16 Aug 2011 19:15:02 -0400
This is one of those things that make my brain itch. I had to puzzle over this...
On Aug 16, 2011, at 4:18 PM, Quincey Morris wrote:
> Noting that a key path like "someObject.someArrayProperty.count" is valid, I think you could envisage key paths of the form "someObject.someArrayProperty.@0" and @1, @2, @3, etc. For this to work, "someObject.someArrayProperty" would have to return a NSArray subclass (or a compatible proxy object) that implements 'valueForUndefinedKey:' and recognizes the "indexing" properties from their key name syntax.
The main drawbacks would be:
* It's a pain to create an NS{Mutable}Array replacement.
* You lose the benefits of Apple's finely-tuned array classes (I'm thinking of the automatic calculating of capacity; plus it might be hard to match them for performance).
* You have to remember to use the replacement class in your own classes.
* You can't use this on existing classes that have array properties.
Thorsten's solution helps by mashing the array index together with the name of the array property, so you can do:
On Aug 16, 2011, at 6:16 PM, Thorsten Hohage wrote:
> producer_0.area_0.vineyards_2.idname
However, your class has to inherit from a class that has his implementation of valueForUndefinedKey:.
I *may* have an approach that gets around these drawbacks, although it looks a little funny.
To summarize the problem, we'd like to be able to say something like
Employee *anEmployee = [aManager valueForKey:@"department.employees.2"];
where this would give us the second element of the employee list for a given manager's department. We can't quite do that, but my approach comes pretty close by inserting a pseudo-key "ARR" *before* the array property:
Employee *anEmployee = [aManager valueForKey:@"department.ARR.employees.2"];
This should work on any class with an array property like "employees".
How it works: there is a category method called "ARR" on NSObject that returns a special wrapper object that makes everything else work. I have a quick and dirty example project that *seems* to show this working with both setting and getting. In my next post I'll attach the relevant source file so anybody interested can sanity-check it.
--Andy
_______________________________________________
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