Search code examples
cocoacocoa-bindingskey-value-coding

Collection Object operator for @firstObject Key-value coding KVC


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!


Solution

  • 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!