CoreData 获取不同的属性值 [英] CoreData get distinct values of Attribute

查看:20
本文介绍了CoreData 获取不同的属性值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将我的 NSFetchRequest 设置为核心数据,以检索实体中特定属性的唯一值.即

I'm trying to setup my NSFetchRequest to core data to retrieve the unique values for a specific attribute in an entity. i.e.

具有以下信息的实体:

  name | rate | factor |
_______|______|________|
John   |  3.2 |    4   |
Betty  |  5.5 |    7   |
Betty  |  2.1 |    2   |
Betty  |  3.1 |    2   |
Edward |  4.5 |    5   |
John   |  2.3 |    4   |

我将如何设置请求以仅返回一个数组:John、Betty、Edward?

How would i set up the request to return an array with just: John, Betty, Edward?

推荐答案

您应该使用后备存储来帮助您获得不同的记录.

You should use the backing store to help you get distinct records.

如果你想得到一个只有 John、Betty、Edward 的数组,你可以这样做:

If you want to get an array with just John, Betty, Edward here's how you do it:

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

// Required! Unless you set the resultType to NSDictionaryResultType, distinct can't work. 
// All objects in the backing store are implicitly distinct, but two dictionaries can be duplicates.
// Since you only want distinct names, only ask for the 'name' property.
fetchRequest.resultType = NSDictionaryResultType;
fetchRequest.propertiesToFetch = [NSArray arrayWithObject:[[entity propertiesByName] objectForKey:@"name"]];
fetchRequest.returnsDistinctResults = YES;

// Now it should yield an NSArray of distinct values in dictionaries.
NSArray *dictionaries = [self.managedObjectContext executeFetchRequest:fetchRequest error:nil];
NSLog (@"names: %@",dictionaries);

这篇关于CoreData 获取不同的属性值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆