Mailing Lists: Apple Mailing Lists
Image of Mac OS face in stamp
valueForKey: on collections [was: Re: Using isMemberOfClass with a tree of subclass of NSManagedObject]
[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

valueForKey: on collections [was: Re: Using isMemberOfClass with a tree of subclass of NSManagedObject]

On Jun 28, 2008, at 1:08 PM, Kyle Sluder wrote:
On Sat, Jun 28, 2008 at 2:14 PM, Bill Bumgarner <email@hidden> wrote:
You want -objectForKey:  -valueForKey: is for key value coding,
-objectForKey: is for extracting objects from a dictionary.

Shouldn't cause a problem.

I thought the collection classes were smart and treated -valueForKey: by sending each object in the collection -valueForKey: and compiling the results in an object arranged in the same way as the original. That way you could have an array of strings and do something like [myArray valueForKey:@"length"] to get an array of lengths corresponding to each instance.

Sort of. Depends on the collection class. The behavior you describe works for NSArray (and NSSet, IIRC). For NSDictionary, the rules are slightly different: ...

If key does not start with “@”, invokes objectForKey:. If key does
start with “@”, strips the “@” and invokes [super valueForKey:]with
the rest of the key.

The real problem is -valueForKeyPath: behaves magically differently on dictionaries from everything else. If the argument contains a "." character, the entire keypath is treated as a single key to - objectForKey: If the entire keypath does not exist in the dictionary, then it falls back to the normal -valueForKeyPath: behavior.

Basically, if you have a "." character in any of your keys, you can find some serious confusion. Say, if you ever use a DNS or reverse DNS names for a key. Like the contents of ~Library/Preferences

-valueForKey:  != -objectForKey:

Which is, frankly, a bit goofy and, thus, the primary reason why I
would avoid using -valueForKey: on a dictionary.

Amen. It's slower, and people reading your code can get very confused.

- Ben


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)

Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden

Visit the Apple Store online or at retail locations.

Contact Apple | Terms of Use | Privacy Policy

Copyright © 2011 Apple Inc. All rights reserved.