NSPredicate: Fetch one of each kind

后端 未结 5 1977
眼角桃花
眼角桃花 2021-02-02 11:49

I want to create an NSFetchRequest for objects like this:

The Object is Car which has an attribute color

5条回答
  •  误落风尘
    2021-02-02 12:29

    If you are targeting iOS 4.0 or later and not using the Core-Data SQL store why not use predicateWithBlock:?

    The following will generate the NSFetchRequest you want.

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

    You could then create a new method to execute the fetch and return the results you want.

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

提交回复
热议问题