NSPredicate:获取各种类型之一

时间:2013-05-07 17:06:31

标签: 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

的东西

5 个答案:

答案 0 :(得分:19)

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


从该页面开始:

  

获取不同的值

     

获取所有特定属性的唯一值   给定实体的实例,您使用。配置获取请求   方法setReturnsDistinctResults :(并传递YES作为参数)。您   还指定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获取它们)

答案 1 :(得分:14)

您是否尝试使用valueForKeyPath?您可以在NSPredicate为您提供的数组中执行类似的操作。

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

它会给你带来你所拥有的鲜明颜色,我不知道它是不是你想要的颜色,但是你可以用@Anupdas这样的颜色告诉你:

答案 2 :(得分: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;
}

然后,您可以创建一个新方法来执行获取并返回所需的结果。

- (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;
}

答案 3 :(得分: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;

答案 4 :(得分: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];
}