views:

349

answers:

1

I have several objects set up in Core Data, one of which is "Deck" and one of which is "Card". "Cards" have several numbered relationships, including "id". "Deck" has a one-to-many relationship with cards.

What's the best way to find the Card in a Deck that has the minimum value to some numbered attribute, such as id?

Clearly I can get the list of cards like this:

NSSet *cardList = self.cards;

I think I can build an expression to get a minimum like this:

NSExpression *keyPathExpression = [NSExpression expressionForKeyPath:@"id"];
NSExpression *minExpression = [NSExpression expressionForFunction:@"min:" 
      arguments:[NSArray arrayWithObject:keyPathExpression]];

But I can't quite suss out how to use that expression to extract the card with the minimum value of id (or just the minimum value of id).

+2  A: 

You can do this using Key-Value coding:

//assuming Card has an Id property which is a number
NSNumber *minId = [deck valueForKeyPath:@"[email protected]"];

NSSet *minCards = [[deck cards] filteredSetUsingPredicate:[NSPredicate predicateWithFormat:@"Id==%@", minId]];

will give the NSSet of Cards whose Id property is equal to the minimum in deck.cards.

See the Key-Value Programming Guide's description of Set and Array Operators for more info.

Barry Wark
Stunningly simple.
Shannon A.
Yes, although I have to look up the exact syntax every time I use it, Key-Value Coding set and array operators make expression some algorithms *very* easy. Ah, the power of a dynamic language.
Barry Wark