代码之家  ›  专栏  ›  技术社区  ›  Oh Danny Boy

NSPredicate-返回列中唯一的实例

  •  0
  • Oh Danny Boy  · 技术社区  · 14 年前

    我想知道是否有一个谓词来返回列中每个唯一的实例。

    3 回复  |  直到 9 年前
        1
  •  0
  •   Marcus S. Zarra    14 年前

    您可以配置 NSFetchRequest 给你回支票。看看它的文档。

        2
  •  0
  •   Community Jaime Torres    7 年前

    @distinctUnionOfArrays Core Data - Getting Unique Rows

        3
  •  0
  •   Oh Danny Boy    14 年前

    - (NSMutableArray *)fetchNeighborhoods {
    
        ProjectNameAppDelegate *appDelegate = (ProjectNameAppDelegate *)[[UIApplication sharedApplication] delegate];
        NSManagedObjectContext *managedObjectContext = appDelegate.managedObjectContext;    
        NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
        NSEntityDescription *entity = [NSEntityDescription entityForName:@"Bar" inManagedObjectContext:managedObjectContext];
    
        NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"neighborhood" ascending:YES];
        NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil];
        [fetchRequest setSortDescriptors:sortDescriptors];
        [fetchRequest setEntity:entity];
    
        // Get array of results.
        NSMutableArray *theResults = [[managedObjectContext executeFetchRequest:fetchRequest error:nil] mutableCopy];
        // Grab unique neighborhoods through NSSet.
        NSSet *uniqueElements = [NSSet setWithArray:[theResults valueForKey:@"neighborhood"]];
        // Dump NSSet uniques into new array.
        NSMutableArray *sortedResults = [[NSMutableArray alloc] initWithArray:[uniqueElements allObjects]]; 
        // Sort the results alphabetically.
        sortedResults = [[sortedResults sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)] mutableCopy];
        // Output unique results for verification.   
        for(int i = 0; i < [sortedResults count];i++){
            NSLog(@"%d. %@", i+1, [sortedResults objectAtIndex:i]); 
        }
    
        [sortDescriptor release];
        [sortDescriptors release];
    
        return sortedResults;
    }