How can I determine the index of an object in an N

2019-08-15 17:28发布

问题:

Currently I am coding the search capability of a UISearchBar using data from a DB that's displayed in a table. I figure out the search results and save them to NSMutableArray *searchResults. Here's how that looks:

- (void) searchGrapesTableView {
    [searchResult removeAllObjects];
    numSearchWines=0;
    for (NSString *str in listOfWines)
    {
        NSRange titleResultsRange = [str rangeOfString:searchBar.text options:NSCaseInsensitiveSearch];
        if (titleResultsRange.length > 0) {
            [searchResult addObject:str];
            numSearchWines++;
        }
    }
}

listOfWines is also an NSMutableArray that contains a list of all the names that can be searched from. IDEALLY, I would like to determine the index of the object in listOfWines that has the matching value and add it to another NSMutableArray, so that way I can later access it really easily. For example, later on when I display the table cells using this search data, I have the following code:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:@"wineCell"];
    //determine how many to add to get the grape ID
    NSInteger grapeID=0;
    for (int i=0; i<indexPath.section; i++) {
        grapeID += [self.tableView numberOfRowsInSection:i];
    }

    Wines *currentWine;
    if (isSearchOn) {
        NSString *cellValue = [searchResult objectAtIndex:(grapeID+indexPath.row)];
        NSInteger index = 0;
        index = [listOfWines indexOfObject:cellValue];
        currentWine = [allWines objectAtIndex:(index)];
    }

    else {
        currentWine = [allWines objectAtIndex:(grapeID+indexPath.row)];
    }

    cell.textLabel.text = currentWine.name;
    return cell;
}

Unfortunately this doesn't work if there are duplicate entries in listOfWines (and subsequently searchResult). That's why it would be so useful to also have their indexes in, for example, an NSMutableArray named searchResultID, so that I can do something like this:

NSInteger theResultID = [searchResultID objectAtIndex:(grapeID+indexPath.row)];
currentWine = [allWines objectAtIndex:theResultID];

回答1:

This sounds like a job for indexesOfObjectsPassingTest:. You should check it out in the NSArray docs. You use it something like this:

NSIndexSet  *indxs = [allWines indexesOfObjectsPassingTest: ^BOOL(NSString *obj, NSUInteger idx, BOOL *stop) {
        return [obj isEqualToString:searchBar.text]];
    }];

So this will loop through all the values in allWines (I'm assuming the objects are strings) and return the indexes of any that match the search string, giving you an index set with any indexes found.