Getting the Minimum Value of an Attribute in a NSSet Made from a One-to-Many Relationship in Core Data

StackOverflow https://stackoverflow.com/questions/1627447

  •  06-07-2019
  •  | 
  •  

Question

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).

Was it helpful?

Solution

You can do this using Key-Value coding:

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

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top