Jesse Gumpo
Jesse Gumpo

Reputation: 4797

Key-Value Coding @UnionOfObjects

I can't figure out what @UnionOfObjects offers that a simple valueForKey: or valueForKeyPath: can't do.

Apple docs:

The @unionOfObjects operator returns an array containing the distinct objects in the property specified by the key path to the right of the operator. Unlike “@distinctUnionOfObjects,” duplicate objects are not removed. The following example returns the payee property values for the transactions in transactions:

NSArray *payees = [transactions valueForKeyPath:@"@unionOfObjects.payee"];

The resulting payees array contains the following strings: Green Power, Green Power, Green Power, Car Loan, Car Loan, Car Loan, General Cable, General Cable, General Cable, Mortgage, Mortgage, Mortgage, Animal Hospital.

In the above example,

NSArray *payees = [transactions valueForKey:@"payee"];

would return the same array of values, but with less code. What am I missing?

Upvotes: 7

Views: 1893

Answers (1)

Tommy
Tommy

Reputation: 100632

All I can think of immediately is that it "returns an array containing ..." (emphasis mine). So it'll be convenient for:

NSSet *someSet = ...;

NSArray *result = [someSet valueForKey:@"@unionOfObjects.whatever"];

It's therefore useful anywhere in Cocoa bindings where you want an NSSet (or other non-array collection) to push data into an NSArray shaped hole.

Upvotes: 3

Related Questions