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.

有帮助吗?

解决方案

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];
    }
}

其他提示

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.

you could use this

BOOL containsName = [[addressCard.name lowercaseString] containsSubstring: [someName lowercaseString]];
if(containsName)
    [results addObject:addressCard.name];
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top