Reputation: 2811
I wrote a method to search for people in address book, and I want the method to be able to find "john bigs" even if I call the method [someAdressBook searchName:@"joh"];
.
My method works for full names, but Im having issues in the partial names, this is my code:
-(NSMutableArray *) searchName:(NSString *) someName{
NSRange range;
NSMutableArray *results = [[NSMutableArray alloc] init];
for (AddressCards *addressCard in book)
{
if (someName != nil && [someName caseInsensitiveCompare:addressCard.name] == NSOrderedSame)
[results addObject:addressCard.name];
else {
range = [addressCard.name rangeOfString:someName];
if (range.location != NSNotFound)
[results addObject:addressCard.name];
}
}
NSLog(@"%@", results);
return results;
}
Please help me get this right.
Upvotes: 2
Views: 2351
Reputation: 7660
You can use NSPredicate like this:
-(NSMutableArray *) searchName:(NSString *) someName {
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"ANY addressCard.name CONTAINS[c] %@", someName];
return [NSMutableArray arrayWithArray:[book filteredArrayUsingPredicate:predicate]];
}
The trick here is the [c]. This is equivalent to case insensitive.
Notice that I'm supposing that book is of NSArray type, if it is of NSMutableArray, using predicate will filter the "original" array.
Upvotes: 1
Reputation: 52227
you could use this
BOOL containsName = [[addressCard.name lowercaseString] containsSubstring: [someName lowercaseString]];
if(containsName)
[results addObject:addressCard.name];
Upvotes: 0
Reputation: 21464
You can do the search in a case-insensitive manner using -[NSString rangeOfString:options:], so you can do it in one step:
for (AddressCards *addressCard in book)
{
if ([addressCard.name rangeOfString:someName options:NSCaseInsensitiveSearch].location != NSNotFound)
{
[results addObject:addressCard.name];
}
}
Upvotes: 4