CoreData获取Attribute的不同值

时间:2011-08-09 18:11:39

标签: ios core-data nsfetchrequest

我正在尝试将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?

4 个答案:

答案 0 :(得分:71)

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

如果你想得到一个只有约翰,贝蒂,爱德华的阵列,你就是这样做的:

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);

答案 1 :(得分:15)

您尝试使用Core Data作为过程数据库,而不是像API那样使用对象图管理器,因此您将找不到一种简单的方法来执行此操作。

在核心数据中没有直接的方法可以做到这一点,因为核心数据与对象而不是值有关。由于托管对象保证是唯一的,因此Core Data并不关心每个对象的值,也不关心它们是重复的还是其他对象的值。

要查找唯一值:

  1. 执行fetch by specific value。这将为您提供一个字典数组,其中包含键name和名称字符串本身的值。
  2. 在(1)中返回的数组上,使用set collection operator返回一组唯一值。
  3. 所以,比如:

    NSSet *uniqueNames=[fetchedNameDicts valueForKeyPath:@"@distinctUnionOfSets.name"];
    

    ...它将返回一组具有唯一值的NSString对象。

答案 2 :(得分:10)

这是Swift 5.x中的一种简单方法:

// 1. Set the column name you want distinct values for
let column = "name"

// 2. Get the NSManagedObjectContext, for example:
let moc = persistentContainer.viewContext

// 3. Create the request for your entity
let request = NSFetchRequest<NSFetchRequestResult>(entityName: "User")

// 4. Use the only result type allowed for getting distinct values
request.resultType = .dictionaryResultType

// 5. Set that you want distinct results
request.returnsDistinctResults = true

// 6. Set the column you want to fetch
request.propertiesToFetch = [column]

// 7. Execute the request. You'll get an array of dictionaries with the column
// as the name and the distinct value as the value
if let res = try? moc.fetch(request) as? [[String: String]] {
    print("res: \(res)")

    // 8. Extract the distinct values
    let distinctValues = res.compactMap { $0[column] }
}

答案 3 :(得分:5)

看看Fetching Specific Property Values,没有必要使用Set来获取不同的值。

相关问题