获取最大值记录**(Coredata)**

时间:2012-07-20 05:24:45

标签: iphone objective-c ios database core-data

我是Core Data的新手,我正在尝试获取具有最大时间戳值的记录。 在下面的代码中,我获得了最大的TimeStamp值,但我希望该记录具有最大的时间戳值。

AppDelegate * appDelegate =(AppDelegate *)[[UIApplication sharedApplication] delegate];

NSManagedObjectContext *context = [appDelegate managedObjectContext];

NSEntityDescription *entity = [NSEntityDescription
                               entityForName:@"EnergyCumulative" inManagedObjectContext:context];


NSFetchRequest *fetchRequest = [[ NSFetchRequest alloc] init];
[fetchRequest setEntity:entity];
NSExpression *keyPathExpression = [NSExpression
                                   expressionForKeyPath:@"TimeStamp"];
NSExpression *ex = [NSExpression expressionForFunction:@"max:" 
                                             arguments:[NSArray arrayWithObject:keyPathExpression]];


NSExpressionDescription *expressionDescription = [[NSExpressionDescription alloc] init];
[expressionDescription setName:@"AvgReading"];
[expressionDescription setExpression:ex];
[expressionDescription setExpressionResultType:NSStringAttributeType];

[fetchRequest setPropertiesToFetch:[NSArray arrayWithObject:expressionDescription]];
[fetchRequest setResultType:NSDictionaryResultType];
[fetchRequest setEntity:entity];


NSError *error;  

NSArray *tripArray = [context executeFetchRequest:fetchRequest error:&error];
 NSLog(@"%@",tripArray);  

在NSLog我得到了 (         {         AvgReading = 1342704600000;     } )

实施例。我有实体 EnergyCumulative ,因为我的属性阅读& TimeStamp ,所以我想要那个有最大时间戳的阅读

1 个答案:

答案 0 :(得分:0)

TimeStamp的类型是什么?

更改

的类型
[expressionDescription setExpressionResultType:NSStringAttributeType];

NSDateAttributeType,如果它是日期类型,或NSDecimalAttributeType,如果它是数字。

顺便说一下,你已经写了[fetchRequest setEntity:entity];两次......(好吧,没什么大不了的)


编辑:

您可以使用

[[tripArray objectAtIndex:0] valueForKey:@"AvgReading"];

获取最大时间戳。 ('@ AvgReading'不是一个好名字我认为,虽然它很好用)

(您可以使用最大时间戳使用NSStringAttributeType ??)

相关问题