0
votes

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];
1
your approach with the NSFetchedResultsController is maybe the solutions. create the NSFetchedResultsController with the specific NSPredicate, NSSortDescription and access only the first an last object with [yourFetchController objectAtIndexPath:]CarlJ

1 Answers

1
votes

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