I mean a got an array with words like:
@[@"Hellobla", @"Hello Kitty", @"Hello Kitty Bla", @"Bla apukitty", @"Bla helkitty"]
i need to sort them like anchored of all words separated by space @" "
.
if i'll type "Hel"
- i will see @"Hellobla", @"Hello Kitty Bla", @"Bla helkitty"
if i'll type "kit"
- i will see @"Hello Kitty Bla", @"Hello Kitty"
if i'll type "bla"
- i will see @"Hello Kitty Bla", @"Bla apukitty", @"Bla helkitty"
etc :)
i do it in block returns array:
// arrayWithData - All Words
// searchWord - Text i try to search with
// arrayToWrite - array to return with words
// arrayToCompare - array with words already added whitch first NSPredicate *beginPredicate = [NSPredicate predicateWithFormat:@"self BEGINSWITH[cd] %@", //searchText];
beginMatch = [self.objects filteredArrayUsingPredicate:beginPredicate];
sortedWithSecondWordArray = ^(NSArray * arrayWithData,
NSString * searchWord,
NSMutableArray *arrayToWrite,
NSArray * arrayToCompare) {
NSString *space = @" ";
for (__strong NSString *string in arrayWithData) {
NSString *staticString = string;
while ([string rangeOfString:space].location != NSNotFound) {
NSRange range = NSMakeRange(0, [string rangeOfString:space].location);
NSString *keyword = [[string stringByReplacingCharactersInRange:range withString:@""] trim];
if (keyword.length > 0
&& [keyword rangeOfString:searchWord options:NSAnchoredSearch].location != NSNotFound
&& ![arrayToCompare containsObject:staticString]
&& ![arrayToWrite containsObject:staticString]) {
[arrayToWrite addObject:staticString];
}
string = keyword;
};
}
return arrayToWrite;
};
It works, but if in my Array 2000 strings and it could be more than 10k. And its really awful. How to optimaze it?
If I have understood your question correctly, then you want to match any string containing word that begins with your search string?
An NSPredicate
with a regular expression can do that, using the \b
word boundary anchor.
NSArray *data = @[@"Hellobla", @"Hello Kitty", @"Hello Kitty Bla", @"Bla apukitty", @"Bla helkitty"];
NSString *searchString = @"Hel"; // Change to other strings
NSString *anchoredPattern = [NSString stringWithFormat: @".*\\b%@.*", searchString];
NSPredicate *anchoredPred = [NSPredicate predicateWithFormat: @"SELF MATCHES[cd] %@", anchoredPattern];
NSArray *filtered = [data filteredArrayUsingPredicate:anchoredPred];
It produces the results you are after, with the possible exception that it includes both "Hello Kitty" and "Hello Kitty Bla" in the results.
If that is not what you want, you might need to filter the result again to exclude strings that are substrings of other strings in the array.