1
votes

I am new to Core Data,I am trying to fetch a record which has maximum Timestamp value. In Following code I am getting the maximum TimeStamp value but I want that record that has maximum timestamp value.

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);  

In NSLog I am getting ( { AvgReading = 1342704600000; } )

Ex. I have Entity EnergyCumulative in that I have attribute Reading & TimeStamp, so I want that reading that has maximum timestamp

1

1 Answers

0
votes

What's the type of your TimeStamp?

Change the type of

[expressionDescription setExpressionResultType:NSStringAttributeType];

to NSDateAttributeType in case it is a Date type, or NSDecimalAttributeType in case it is a Number.

By the way, you've wrote [fetchRequest setEntity:entity]; two times... (well, not a big deal)


EDIT:

You can use

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

to get your max timestamp. ('@AvgReading' is not a good name I think, though it well work)

(You can get the max timestamp just use Use NSStringAttributeType??)