Search code examples
objective-ciosnsstringnsarraynsdictionary

loop through array of dictionaries to find a value


I have an array of dictionaries that I would like to go through to find a matching value that I can then Count == Nth item of the array

Each item of the array looks like this

HMOD = 0;
MID = 39;
MOD = SOMETHING; // looking for this value
ID = 50;

So I would like to create a loop that goes through the array until it finds the matching value, then I use the number in the count as an reference to Index path in the next view..

I have written this peice of code which dosnt work... but hopefully it gives you an idea of the loop I am trying to create.

int count = 0;
while (singleName != [[ModArray valueForKey:@"MOD"] objectAtIndex:count]) {
                    count ++;
                    NSLog(@"%i", count);
                }

SingleName is a NSString that I am using to match the MOD value in ModArray... Any help would be greatly appreciated.


Solution

  • Here is a simpler solution by using valueForKey on the array of dictionaries,

    Assuming that your modArray is like this,

    NSArray *modArray = [NSArray arrayWithObjects:[NSDictionary dictionaryWithObject:@"0" forKey:@"HMOD"],
                           [NSDictionary dictionaryWithObject:@"39" forKey:@"MID"],
                           [NSDictionary dictionaryWithObject:@"something" forKey:@"MOD"],
                           [NSDictionary dictionaryWithObject:@"50" forKey:@"ID"], nil];
    

    And singleName has a value as "something"

        NSString *singleName = @"something";
    

    Fetch the array from modArray which has an object with key as "MOD",

        NSArray *array = [modArray valueForKey:@"MOD"];
    

    Check if singleName is present in this array. If yes, then get the first index of that object which will be same as the index of dictionary with key "MOD" in modArray.

        if ([array containsObject:singleName]) {
            NSLog(@"%d", [array indexOfObject:singleName]);
        } else {
            NSLog(@"%@ is not present in the array", singleName);
        }
    

    Update: If you want to do it in your way, only mistake was you were using != whereas you should have used isEqualToString. You should have done like this,

    int count = 0;
    while (![singleName isEqualToString:[[modArray valueForKey:@"MOD"] objectAtIndex:count]]) {
                        count ++;
                        NSLog(@"%i", count);
                    }