7

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?

Jesse Gumpo
  • 4,777
  • 1
  • 20
  • 29

1 Answers1

3

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.

Tommy
  • 99,986
  • 12
  • 185
  • 204
  • 1
    Warning for future readers: when I tried this, I got: `'NSInvalidArgumentException', reason: '[<__NSSetI 0x7ff069d02140> valueForKeyPath:]: this class does not implement the unionOfObjects operation.` (in a playground), so it may not be safe to use `@unionOfObjects` on an NSSet at all. – Alex Pretzlav Jul 09 '15 at 00:31