Prajoth
Prajoth

Reputation: 900

How to search array of strings

I am creating an application where the user can select multiple cells from a table, and each time a cell is selected, it is being added to an NSMutableArray. The table contains names of different countries. Once all the countries are selected, how do I search for which countries are selected? For example, how do I check if the user selected United States for example?

I have this in my didSelectRow for my table:

if ([selectedCell accessoryType] == UITableViewCellAccessoryNone) {
        [selectedCell setAccessoryType:UITableViewCellAccessoryCheckmark];
        [listofCountriesselected addObject:[NSNumber numberWithInt:indexPath.row]];

    } 
    else {
        [selectedCell setAccessoryType:UITableViewCellAccessoryNone];
        [listofCountriesselected removeObject:[NSNumber numberWithInt:indexPath.row]];

    }

Upvotes: 1

Views: 187

Answers (1)

bryanmac
bryanmac

Reputation: 39306

You can add the countries to the NSMutableArray and check containsObject. In this case, I'm adding a string - you can add via some country identifier but you need to check by the same country identifier (whatever you choose). Row number is not a good identifier - it's not stable.

NSMutableArray *list = [[NSMutableArray alloc] init];
[list addObject:@"US"];
[list addObject:@"CN"];
NSLog(@"usa? %d", (int)[list containsObject:@"US"]);

An even faster way to check if a country has been selected would be to add the country to an NSMutableSet when selected.

An NSMutableSet is a hash set so look ups are very fast.

NSMutableSet *lookup = [[NSMutableSet alloc] init];
[lookup addObject:@"US"];
[lookup addObject:@"CN"];

NSLog(@"usa? %d", (int)[lookup containsObject:@"US"]);

Both output 1.

The key difference is the NSMutableArray is an order list of items - a list. The NSMutableSet is optimized for contains - just a set. For example, if you wanted to not only track what's selected but the order they selected them in, then you need a mutable array. It's also not uncommon for apps to contain aggregate data structures to answer ordering and contains type questions.

BTW, here's how you can get all the ISO country codes

NSArray *countryCodes = [NSLocale ISOCountryCodes];
for (NSString *cc in countryCodes)
{
    NSLog(@"cc: %@", cc);
}

Upvotes: 2

Related Questions