我正在尝试将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 |
我将如何设置仅返回一个数组的请求:John,Betty,Edward?
最佳答案
您应该使用后备存储来帮助您获取不同的记录。
如果您只想使用John,Betty和Edward来获得数组,则方法如下:
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);