5
votes

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?

3

3 Answers

5
votes

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

2
votes
  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.

0
votes

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