user1904273
user1904273

Reputation: 4764

Access values in two dimensional NSArray in Objective-c

For the following two-dimensional array, I'd like to search the names for say John and then be able to retrieve the name John Smith and the id for John.

NSArray *employees = @[@[@"John Smith",@"1"],@[@"Ken Robinson",@"2"],@[@"Albert Jones",@"3"],@[@"Richard Johnson",@"4"]];

I can create the array, using the above syntax. How would I search it for John and retrieve John Smith, 2 and access the employee's id, 2, something like employees[0][1] where 0 is the index and 1 is the dimension for id.

This is how I would search the array in one dimension but I'm confused on syntax for searching with a 2-d array.

-(NSString *)findNameInArray:(NSString*) searchstring
NSArray* employees = @[@"John Smith"@"Ken Robinson",@"Albert Jones",@"Richard Johnson"];
for (long i=0;i<[employees count];i++) {
            name = employees[i];
            if ( [name localizedCaseInsensitiveCompare:searchstring] == NSOrderedSame) {
                return name;
            }//close loop
return @"":
    }

Upvotes: 0

Views: 96

Answers (2)

Sasha  Tsvigun
Sasha Tsvigun

Reputation: 351

Yes, NSPredicate is the best solution in this case.

Upvotes: 0

danh
danh

Reputation: 62686

Maybe there's a good reason to have an array of arrays. If so, you can filter the outer array with a predicate that applies to the inner array...

// look for @"John" anywhere in the 1st element (case insensitive)
NSPredicate *p = [NSPredicate predicateWithFormat:@"SELF[0] CONTAINS[cd] %@", @"John"];
NSArray *matches = [employees filteredArrayUsingPredicate:p];

You can also find a match to the start of the string with BEGINSWITH

Upvotes: 2

Related Questions