如何找到coredata中存储的日期的最大值?

时间:2014-08-01 01:37:25

标签: ios core-data ios7

我在核心数据中创建了一个实体,它包含Date类型的属性。那么如何才能找到存储在那里的最大日期值。

1 个答案:

答案 0 :(得分:2)

NSString * yourEntityName = @"Entity";
NSString * yourDateAttributeName = @"date";

NSFetchRequest * fetchRequest = [[NSFetchRequest alloc] init];

NSEntityDescription *entity = [NSEntityDescription entityForName:yourEntityName
                                          inManagedObjectContext:ctx];
[fetchRequest setEntity:entity];
[fetchRequest setPropertiesToFetch:@[yourDateAttributeName]];
[fetchRequest setFetchLimit:1];

// Edit the sort key as appropriate.
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:yourDateAttributeName ascending:NO];
NSArray *sortDescriptors = @[sortDescriptor];

[fetchRequest setSortDescriptors:sortDescriptors];

NSError * error = nil;
NSArray * results = [ctx executeFetchRequest:fetchRequest error:&error];

NSManagedObject * yourEntityObject = [results firstObject];

NSDate * date = [yourEntityObject valueForKey:yourDateAttributeName];