Created
February 18, 2016 16:13
-
-
Save AdityaDeshmane/0699f495f69a876e3cb0 to your computer and use it in GitHub Desktop.
iOS: Full name search using predicate
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-(NSArray*) dataSourceForSearchString:(NSString*) searchedText | |
{ | |
NSString *strTrimmedSearchText = [searchedText stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]]; | |
NSArray *array = [strTrimmedSearchText componentsSeparatedByString:@" "]; | |
NSPredicate *predicate = nil; | |
/* | |
@property (nonatomic, strong) NSString *firstName; | |
@property (nonatomic, strong) NSString *midName; | |
@property (nonatomic, strong) NSString *lastName; | |
*/ | |
if(array.count == 1) | |
{ | |
predicate = [NSPredicate predicateWithFormat:@"firstName CONTAINS[c] %@ OR lastName CONTAINS[c] %@", | |
strTrimmedSearchText, | |
strTrimmedSearchText]; | |
} | |
else if (array.count == 2)//search contains firstname and lastname | |
{ | |
NSString *firstName = [array objectAtIndex:0]; | |
NSString *lastName = [array objectAtIndex:1]; | |
//firstName should exact match, lastname should begin with text | |
predicate = [NSPredicate predicateWithFormat:@"(firstName LIKE[c] %@ AND lastName BEGINSWITH[c] %@)", | |
firstName, | |
lastName]; | |
} | |
else if(array.count == 3)//search contains firstname, middlenamey and lastname | |
{ | |
NSString *firstName = [array objectAtIndex:0]; | |
NSString *midName = [array objectAtIndex:1]; | |
NSString *lastName = [array objectAtIndex:2]; | |
//firstName and middle name should exact match, lastname should begin with text | |
predicate = [NSPredicate predicateWithFormat:@"(firstName LIKE[c] %@ AND midName LIKE[c] %@ AND lastName BEGINSWITH[c] %@)", | |
firstName, | |
midName, | |
lastName]; | |
} | |
else | |
{ | |
return [NSArray new]; | |
} | |
NSArray *filteredArray = [_arrayBeneficiarySummaryList filteredArrayUsingPredicate:predicate]; | |
return filteredArray; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment