开发者

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

开发者 https://www.devze.com 2023-03-27 21:57 出处:网络
for example, I have a managed object sa开发者_运维问答ve in coredata like @interface team : NSManagedObject

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


  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.


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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号