NSPredicate:获取各种类型之一 [英] NSPredicate: Fetch one of each kind

查看:73
本文介绍了NSPredicate:获取各种类型之一的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想为这样的对象创建 NSFetchRequest

I want to create an NSFetchRequest for objects like this:

对象 Car ,其属性 颜色
我有四辆车:

The Object is Car which has an attribute color. I have four cars:

car1.color = red
car2.color = red
car3.color = blue
car4.color = green

我想创建一个 NSPredicate 每种颜色只选择一辆车(它选择哪辆车无关紧要。

I want to create an NSPredicate that selects only one car for each color(it doesn't matter which car it selects.

我该怎么办?实现这个目标?

How can I achieve this?

事实上,我正在寻找类似于SQL中的 DISTINCT 之类的东西

In fact I'm looking for something similar like a DISTINCT in SQL

推荐答案

核心数据支持支持获取不同的值.Apple甚至在这里提供示例代码: http://developer.apple.com/library/ios/#documentation/DataManagement /Conceptual/CoreDataSnippets/Articles/fetchExpressions.html

Core Data does support fetching distinct values. Apple even provides sample code here: http://developer.apple.com/library/ios/#documentation/DataManagement/Conceptual/CoreDataSnippets/Articles/fetchExpressions.html

从该页面:


获取不同的值



要在给定实体的所有
实例中获取特定属性的唯一值,请使用
方法setReturnsDistinctResults:配置获取请求(并将YES作为参数传递)。你
还指定fetch应该返回字典而不是
托管对象,以及要获取的属性的名称。

Fetching Distinct Values

To fetch the unique values of a particular attribute across all instances of a given entity, you configure a fetch request with the method setReturnsDistinctResults: (and pass YES as the parameter). You also specify that the fetch should return dictionaries rather than managed objects, and the name of the property you want to fetch.

Swift 2.0

let context:NSManagedObjectContext! = <#Get the context#>
let entity = NSEntityDescription.entityForName( "<#Entity name#>",  inManagedObjectContext:context )
let request = NSFetchRequest()
request.entity = entity
request.resultType = .DictionaryResultType
request.returnsDistinctResults = true
request.propertiesToFetch = [ "<#Attribute name#>" ]

var objects:[[String:AnyObject]]?
do
{
    try objects = context.executeFetchRequest( request )
}
catch
{
    // handle failed fetch
}

Obj-C

NSManagedObjectContext *context = <#Get the context#>;  

NSEntityDescription *entity = [NSEntityDescription  entityForName:@"<#Entity name#>" inManagedObjectContext:context];  
NSFetchRequest *request = [[NSFetchRequest alloc] init]; 
[request setEntity:entity]; 
[request setResultType:NSDictionaryResultType];
[request setReturnsDistinctResults:YES]; 
[request setPropertiesToFetch:@[@"<#Attribute name#>"]];  

// Execute the fetch. 

NSError *error = nil; 
id requestedValue = nil; 
NSArray *objects = [context executeFetchRequest:request error:&error]; 
if (objects == nil) {
    // Handle the error. 
} 

(一个问题是结果将作为词典返回 - 如果您需要这些对象,您可以通过ID获取另一个获取对象

(One "gotcha" is that the results will be returned as dictionaries--if you need the objects you can do another fetch to get them by ID)

这篇关于NSPredicate:获取各种类型之一的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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