how do you select the entry with the max value in coredata?
for example, I have a managed object sa开发者_运维问答ve 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?
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
Use an
NSSortDescriptor
for your fetch request using NSFetchRequests's-setSortDescriptors:
method to specify an order for fetching objects.Specify a fetch limit using NSFetchRequest's
-setFetchLimit:
to get only the first object.
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
精彩评论