Tuesday, October 27, 2009

More sophistication with NSArray

This stackoverflow post hightlights another NSArray method I haven't used:

- (id)valueForKey:(NSString *)key

This method
"Returns an array containing the results of invoking valueForKey: using key on each of the receiver's objects."
The example is to make an array containing all the values obtained for a given key. The objects could be custom objects, dictionaries or whatever. Another answer says to do it by using the function below on an NSArray of objects:

- (id)valueForKeyPath:

as in:

[people valueForKeyPath:@"@distinctUnionOfObjects.state"]

It wasn't clear to me how one would know that. It's not listed under the NSArray documentation. And what is this @distinctUnionOfObjects thingie? Ah...it is added under KVC.

"Array operators allow you to specify operations to be performed on a collection's items using a key path of the form keyPathToArray.@operator.keyPathToProperty."

Next time I want the object in an array with the maximum value for a particular key, I'll have to remember to use @max.

No comments: