Alex Stone
Alex Stone

Reputation: 47364

iPhone how to efficiently get the first and last Core Data entity with NSDate property?

I have a fairly large set of Core Data entities with a date property. I'm creating a report from the entities and need to find the report date range. There are ~1000 records within the report.

I'm thinking of getting the fetched objects array from my NSFetchedResultsController and sorting the array using date sort descriptor. Then getting the first and last object of that array to determine the date range. I seem to recall that date operations are expensive and am not sure if sorting an array that way, getting a 1000 element array back is a good idea.

Is there some other core data or predicate trick that I can use to query my core data stack to find an object with the minimum or maximum date?

Here's the code that I'm currently using, but am wandering if there's something faster and more efficient:

 NSSortDescriptor* sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"date" ascending:YES];
    NSArray* sortDescriptors = [NSArray arrayWithObject:sortDescriptor];

    NSArray* sortedDateArray = [NSMutableArray arrayWithArray:[fetchedResultsController.fetchedObjects sortedArrayUsingDescriptors:sortDescriptors]] ;       

    NSManagedObject* firstDateObject = [sortedDateArray objectAtIndex:0];  
    NSManagedObject* lastDateObject = [sortedDateArray lastObject];

Upvotes: 0

Views: 1208

Answers (1)

Jody Hagins
Jody Hagins

Reputation: 28419

No need to use a FetchedResultsController. Just use a simple FetchRequest, and take advantage of the aggregate functionality.

The following document actually has an example of fetching based on the minimum date attribute of an entity.

http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/CoreData/Articles/cdFetching.html#//apple_ref/doc/uid/TP40002484-SW6

Upvotes: 1

Related Questions