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).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With