CoreData获取Attribute的不同值

eph*_*lip 31 core-data nsfetchrequest ios

我正在尝试将我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   |
Run Code Online (Sandbox Code Playgroud)

我如何设置返回数组的请求:John,Betty,Edward?

All*_*tor 73

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

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

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);
Run Code Online (Sandbox Code Playgroud)


Tec*_*Zen 16

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

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

要找到唯一值:

  1. 按特定值执行提取.这将为您提供一个字典数组,其中包含键name和名称字符串本身的值.
  2. 在(1)中返回的数组上,使用set collection运算符返回一组唯一值.

所以,像:

NSSet *uniqueNames=[fetchedNameDicts valueForKeyPath:@"@distinctUnionOfSets.name"];
Run Code Online (Sandbox Code Playgroud)

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

  • +1 这就是我要说的,只是我会选择`@"distinctUnionOfObjects.name"`。我不相信有区别。 (2认同)

Joh*_*rug 15

这是 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] }
}
Run Code Online (Sandbox Code Playgroud)

  • 啊谢谢!实际上我错了,我意识到在为我的实体创建请求时(步骤 3),我需要类型为“NSFetchRequest&lt;NSDictionary&gt;”。这解决了它! (2认同)

Ale*_*les 5

看一下获取特定属性值,没有必要使用Set来获取不同的值.