NSFetchRequest to show results in particular order
Suppose I have one entity 'Person' in core data. Now i want to search all persons. Either firstname beginning match or lastname beginning match. For eg : 1) Amit Gupta 2) Ajay Gulati 3) Gunjan Aggarwal
Searching for 'Gu' shows names that match firstname first, then those that match lastname therefore result is :
Gunjan Aggarwal Ajay Gulati Amit Gupta
One option : Fetch all objects , store them in array and then sort. But what if the search results are very big in number
Second option : Use NSFetchedResultsController This will fetch all matching but not in the required manner(firstname before lastname). Cant use sort descriptors as it is not sorting on any key, but upon matching.
Can anybody help ?
EDIT : First name and lastname are two different attributes of 'Person' entity. Either Firstname matches or Lastname matches.
I want results with 'Firstname' match before than results with 'Lastname' match.
If you use sort descriptor, which 'Key' or 'attribute' will you mention ???
Try to set Sort Descriptors before fetching:
NSSortDescriptor * firstNameDescriptor;
firstNameDescriptor = [[NSSortDescriptor alloc] initWithKey:@"firstName"
ascending:YES
selector:@selector(localizedCaseInsensitiveCompare:)];
NSSortDescriptor * lastNameDescriptor;
lastNameDescriptor = [[NSSortDescriptor alloc] initWithKey:@"lastName"
ascending:YES
selector:@selector(localizedCaseInsensitiveCompare:)];
[firstNameDescriptor release];
[lastNameDescriptor release];
[fetchRequest setSortDescriptors:[NSArray arrayWithObjects:firstNameDescriptor, lastNameDescriptor, nil]];
then fetch your desired persons.
After you got a sorted result, in order to match your searching, you might need to resort it:
- (NSComparisonResult)compare:(id)anotherOne {
// if the first name matches the searching key word, return NSOrderedAscending;
// else return [self.firstName localizedCaseInsensitiveCompare:anotherOne.firstName];
}
then just apply this to your search result array with sortedArrayUsingSelector:
method. No testing code available, but I think you can figure it out by yourself then. ;)
Use a transient property sortName
in your Core Data object, make it compare the firstName
and lastName
properties and just return whichever comes first alphabetically.
Now just use this property as your sortDescriptor
and you should get the result you are after.
Something like this...
- (NSString *)sortName
{
[self willAccessValueForKey:@"sortName"];
NSString *string = nil;
if ([self.firstName compare:self.lastName] == NSOrderedAscending) {
string = self.firstName;
} else {
string = self.lasttName;
}
[self didAccessValueForKey:@"sortName"];
return string;
}
Use two fetch requests. When you're providing data to the view, display the results of the first fetch request, followed by the results of the second.
链接地址: http://www.djcxy.com/p/36132.html