NSPredicate - returning ever unique instance in a column
I was wondering if there was a predicate to return every unique instance in a开发者_如何学JAVA column.
You can configure the NSFetchRequest
to return uniques for you. Take a look at its documentation.
@distinctUnionOfArrays
might work, depending on your situation: Core Data - Getting Unique Rows
Below is the code used to solve the problem.
- (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;
}
精彩评论