23

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

ObjectCar一个attribute color. _ 我有四辆车:

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

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

我怎样才能做到这一点?

事实上,我正在寻找类似DISTINCTSQL的东西

4

5 回答 5

20

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


从该页面:

获取不同的值

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

斯威夫特 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
}

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

于 2013-07-12T08:00:41.437 回答
14

你试过用valueForKeyPath吗?您可以在 NSPredicate 提供给您的数组中执行类似的操作。

NSArray* distinctColors = [cars valueForKeyPath:@"@distinctUnionOfObjects.color"];

它将返回给您您所拥有的独特颜色,我不知道它是否是您想要的,但是使用这些颜色您可以执行@Anupdas 所说的类似操作:

于 2013-07-05T15:40:33.753 回答
3

如果您的目标是 iOS 4.0 或更高版本并且不使用 Core-Data SQL 存储,为什么不使用predicateWithBlock:

以下将生成NSFetchRequest您想要的。

- (NSFetchRequest*) fetchRequestForSingleInstanceOfEntity:(NSString*)entityName groupedBy:(NSString*)attributeName
{
  __block NSMutableSet *uniqueAttributes = [NSMutableSet set];

  NSPredicate *filter = [NSPredicate predicateWithBlock:^(id evaluatedObject, NSDictionary *bindings) {
    if( [uniqueAttributes containsObject:[evaluatedObject valueForKey:attributeName]] )
      return NO;

    [uniqueAttributes addObject:[evaluatedObject valueForKey:attributeName]];
    return YES;
  }];

  NSFetchRequest *req = [NSFetchRequest fetchRequestWithEntityName:entityName];
  req.predicate = filter;

  return req;
}

然后,您可以创建一个新方法来执行 fetch 并返回您想要的结果。

- (NSArray*) fetchOneInstanceOfEntity:(NSString*)entityName groupedBy:(NSString*)attributeName
{
  NSFetchRequest *req = [self fetchRequestForSingleInstanceOfEntity:entityName groupedBy:attributeName];

  // perform fetch
  NSError *fetchError = nil;
  NSArray *fetchResults = [_context executeFetchRequest:req error:&fetchError];

  // fetch results
  if( !fetchResults ) {
    // Handle error ...
    return nil;
  }

  return fetchResults;
}
于 2013-07-08T05:28:16.930 回答
0

试试这个:

NSFetchRequest *request = [[NSFetchRequest alloc] init];
NSEntityDescription *entity =
[NSEntityDescription entityForName:@"Selected_data"
            inManagedObjectContext:self.managedObjectContext];
[request setEntity:entity];
NSPredicate *predicatecnName = [NSPredicate predicateWithFormat:@"countries contains[cd] %@", Countryid];
NSPredicate *predicateLn = [NSPredicate predicateWithFormat:@"languages contains[cd] %@", languageid];
NSArray *subPredicates = [NSArray arrayWithObjects:predicatecnName, predicateLn, nil];

NSPredicate *predicate = [NSCompoundPredicate andPredicateWithSubpredicates:subPredicates];


[request setPredicate:predicate];
NSMutableArray *sendfd=[[NSMutableArray alloc] init];
NSError *error;
NSArray *array1 = [self.managedObjectContext executeFetchRequest:request error:&error];


if (array1 != nil) {


    for (Selected_data *sld in array1)
    {

        [sendfd addObject:sld.providers];
    }


}
else {

}
return sendfd;
于 2013-07-08T11:43:10.333 回答
0

试试这个:

    NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:@"Cars"];
    NSArray *arrayValues = [self.managedObjectContext executeFetchRequest:fetchRequest error:&error];

if (arrayValues.count != 0) {
     NSDictionary *result = [NSDictionary dictionaryWithObjects:arrayValues
                           forKeys:[arrayValues valueForKey:@"color"]];
     return [result allValues];
}
于 2013-07-08T12:40:45.267 回答