iphone - NSPredicate:每种取一个

标签 iphone ios objective-c nspredicate nsfetchedresultscontroller

我想为这样的对象创建一个 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/

相关文章:

ios - 无法执行自动转场

ios - 如何从另一个 View (swift 4)对选项卡栏 Controller 中的特定 View 执行 performSegue

ios - 如何修复快速链接器错误 "framework not found GTMSessionFetcher clang"

objective-c - NSTableView 中用于打开文件的按钮

ios - 通过共享服务器发送推送通知

ios - 按下 UITapGestureRecognizer

iphone - 如何在其他应用程序中集成 aurioTouch 应用程序功能?

iphone - 处理从 iPhone 应用程序 'lite' 到 'pro' 版本的数据迁移

iphone - 横向模式的 curl 效果

ios - 在 iOS 上使用移动 VLC 播放 rtsp 流时出现绿屏