MeloS
MeloS

Reputation: 7938

how do you select the entry with the max value in coredata?

for example, I have a managed object save in coredata like

@interface team : NSManagedObject

@property(nonatomic)NSNumber* teamID;

@end

I have successfully saved some teams with unique teamID in coredata, now I want to get the team with the max teamID, how do I do this?

I used to get all teams and sort them, but this would bring large overhead to make the fetched array, any better idea?

Upvotes: 5

Views: 3806

Answers (3)

Chaitanya Gupta
Chaitanya Gupta

Reputation: 4053

  1. Use an NSSortDescriptor for your fetch request using NSFetchRequests's -setSortDescriptors: method to specify an order for fetching objects.

  2. Specify a fetch limit using NSFetchRequest's -setFetchLimit: to get only the first object.

Upvotes: 2

adonoho
adonoho

Reputation: 4339

user465191,

Here's what I do:

NSNumber *max = [teams valueForKeyPath: @"@max.teamID"];

NSPredicate *p = [NSPredicate predicateWithFormat: @"%K == %@", @"teamID", max];

Team *team = [[teams filteredSetUsingPredicate: p] anyObject];

It is more cumbersome than I desire but it does work.

Andrew

Upvotes: 0

user745098
user745098

Reputation:

Using NSExpression is one of the ways to do so. This has been described with a complete example under the Fetching Specific Values section in Core Data Programming Guide

Upvotes: 5

Related Questions