0

I'm often required to retrieve the 1st object belonging to a Set. (Using that object as a representative of that set.)

I envision a Collection Object operator, akin to the

@unionOfObjects

BUT clearly

@firstObject

Is it possible to create such a Collection operator!

Gabe Rainbow
  • 3,658
  • 4
  • 32
  • 42

1 Answers1

1

Currently there's no way to define custom collection operators. However, due to some internal magic there is a funny solution:

    NSSet *testSet = [NSSet setWithArray:@[@"one", @(1)]];

    id object = [testSet valueForKey:@"@anyObject"];
    NSLog(@"anyObject (%@): %@", NSStringFromClass([object class]), object);

UPD: Forgot to mention another handy trick: you can use @lastObject on NSArray!

Anton
  • 2,342
  • 15
  • 17
  • the `anyObject` might work. thanks. ill give it a shot. on initial viewing, if you have the nsset why not just do [testSet anyObject] versus [testSet valueForKey@"anyObject"]. essentially, it looks like some accessor methods (lastObject, anyObject) for Sets and Arrays are key value coded. – Gabe Rainbow Jun 19 '13 at 22:00
  • @GabeRainbow, your question was about using collection operators. You can definitely use anyObject. Warning, valueForKey:@"anyObject" will not work. valueForKey:@"@anyObject" will. This is due to some implementation details of collection operators. – Anton Jun 20 '13 at 08:09
  • thanks for the clarification there. i noted that @"" misspelling in the Apple documents that must cause some headaches. For sure anyObject will work for my purpose, since Im seeking any representative object in the set and not a particular one, first last whatever. – Gabe Rainbow Jun 20 '13 at 08:16