开发者

I try to use setReturnsDistinctResults to get distinct results with Core Data but can't make it work properly

开发者 https://www.devze.com 2023-01-14 18:15 出处:网络
I\'ve an Core Data entity called \"Themes\" with 4 properties. One of them is called \"name\". This property is not unique. I would like to retrieve a list of all the names contained in the data.

I've an Core Data entity called "Themes" with 4 properties. One of them is called "name". This property is not unique. I would like to retrieve a list of all the names contained in the data.

It seems that I need to use the setReturnesDistinctResults:YES option of the fetch request bu开发者_如何学编程t I can't make it work. Is there anything wrong in the code below?

NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
// entity
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Themes" inManagedObjectContext:_context];
[fetchRequest setEntity:entity];

// sort descriptor
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"name" ascending:YES];
NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil];
[fetchRequest setSortDescriptors:sortDescriptors];

// return distinct
NSDictionary *entityProperties = [entity propertiesByName];
[fetchRequest setPropertiesToFetch:[NSArray arrayWithObject:[entityProperties objectForKey:@"name"]]];
[fetchRequest setReturnsDistinctResults:YES];

NSError *error;
NSArray *fetchedObjects = [_context executeFetchRequest:fetchRequest error:&error];

for (Themes *theme in fetchedObjects) {
    NSLog(@"Theme = %@", theme.name);
}

[fetchRequest release];
[sortDescriptor release];
[sortDescriptors release];


i believe you also have to set this:

 [fetchRequest setResultType:NSDictionaryResultType];

to make it work.

0

精彩评论

暂无评论...
验证码 换一张
取 消