我想为这样的对象创建一个NSFetchRequest:
ObjectCar,它具有attribute color
我有四辆车:

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

我想创建一个NSPredicate,每种颜色只选择一辆车(选择哪辆车都没关系。

我怎样才能做到这一点?

实际上,我正在寻找类似SQL中的DISTINCT的内容

最佳答案

核心数据确实支持获取不同的值。苹果甚至在此处提供示例代码:http://developer.apple.com/library/ios/#documentation/DataManagement/Conceptual/CoreDataSnippets/Articles/fetchExpressions.html

在该页面上:



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获取它们)

关于iphone - NSPredicate:提取每种,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/16424720/

10-11 14:56