gpt4 book ai didi

iphone - NSPredicate:每种取一个

转载 作者:IT王子 更新时间:2023-10-29 08:05:19 27 4
gpt4 key购买 nike

我想为这样的对象创建一个 NSFetchRequest:

ObjectCar,它有一个 attribute color。我有四辆车:

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

我想创建一个NSPredicate,它只为每种颜色选择一辆汽车(它选择哪辆汽车并不重要。

我怎样才能做到这一点?

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

最佳答案

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


从那个页面:

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

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

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com