我在核心数据中创建了一个实体,它包含Date类型的属性。那么如何才能找到存储在那里的最大日期值。
答案 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];