CoreData获得不同的属性值
我试图将我的NSFetchRequest
设置为核心数据来检索实体中特定属性的唯一值。 即
具有以下信息的实体:
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 |
我将如何设置请求返回一个数组只是:约翰,贝蒂,爱德华?
您应该使用后备存储来帮助您获得不同的logging。
如果你想得到一个约翰,贝蒂,爱德华这是你如何做:
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);
您正在尝试像使用过程数据库那样使用Core Data,而不是像API所预期的那样使用对象图pipe理器,所以您不会find一个简单的方法来执行此操作。
核心数据中没有直接的方法来做这件事,因为核心数据是关注对象而不是值。 由于托pipe对象保证是唯一的,因此核心数据并不太在意每个对象的值,或者它们是重复的还是其他对象的值。
要find独特的价值:
- 按特定值执行抓取 。 这将为您提供一个字典数组,其中包含一个键
name
和一个名称string本身的值。 - 在(1)中的返回数组上使用set集合运算符来返回一组唯一值。
所以,像这样的:
NSSet *uniqueNames=[fetchedNameDicts valueForKeyPath:@"@distinctUnionOfSets.name"];
…将返回一组具有唯一值的NSString对象。
查看获取特定属性值 ,不需要使用Set来获取不同的值。