0
votes

I have a table with a single NSDate attribute. The table contains records whose NSDate attribute is populated with various dates. I need to create a request that retrieves only the distinct years within this NSDate attribute.

For example, if my table contains the following entries:

date |stringValue
01-20-2013|"foo"
03-23-2013|"bar"
04-24-2014|"baz"

The core data fetch request will return the following in an array:

2013
2014

2

2 Answers

1
votes

I would recommend you fetch the data from Core Data using an NSFetchRequest and then use an NSDateFormatter to present the data in the required format to the user interface, or where ever it needs to be used. I'm not sure it's possible to do what you want purely within Core Data, or at least if it is, the above might be simpler. Always go with The Simplest Possible Thing.

0
votes

First you have to fetch distinct values like this

NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:@"MyEntity"];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"MyEntity" inManagedObjectContext:self.managedObjectContext];

// Since you only want distinct date, only ask for the 'date' property.
fetchRequest.resultType = NSDictionaryResultType;
fetchRequest.propertiesToFetch = [NSArray arrayWithObject:[[entity propertiesByName] objectForKey:@"date"]];
fetchRequest.returnsDistinctResults = YES;

// Now it should yield an NSArray of distinct values.
NSArray *distinctDateArray = [self.managedObjectContext executeFetchRequest:fetchRequest error:nil];

then usig NSDateFormatter get only exact year values you want like this.

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy"];
for(NSDate *date in distinctDateArray)
{
NSLog(@"Date: %@", [dateFormatter stringFromDate:date]);
}