some_id
some_id

Reputation: 29896

Fetching set of NSManagedObjects using attribute

How does one fetch a set of unique managed objects by requesting a specific attribute to be checked.

e.g. A number of people objects and I would like to retrieve all the unique names, one managed object for each unique name, sorted by name.

Upvotes: 0

Views: 139

Answers (1)

Lorenzo B
Lorenzo B

Reputation: 33428

What about using a request like this

NSFetchRequest *request = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Person" inManagedObjectContext:managedObjectContext];
request.entity = entity;
request.propertiesToFetch = [NSArray arrayWithObject:[[entity propertiesByName] objectForKey:@"name"]];
request.returnsDistinctResults = YES;
request.resultType = NSDictionaryResultType;

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

NSError *error = nil;
NSArray *distinctResults = [managedObjectContext executeFetchRequest:request error:&error];
// Use distinctResults

Try and let me know.

P.S. Code is ARC enabled. If you are not using it, call release when necessary.

Upvotes: 3

Related Questions