Reputation: 7938
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
Reputation: 4053
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.
Upvotes: 2
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
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