Friday, January 13, 2012

Find NSDictionary in NSArray with Certain Value

Current project got lots of data in NSArrays and NSDictionaries. Nothing against them, extremely useful data structures. Just got to finetune my hammer a bit (since hammer is what I got and thus everything looks like a nail).

So how do you find a certain NSDictionary from NSArray containing a requested key? Two easy ways here:

This is what I usually did. Simple code, easy to understand, easy to debug, self-documenting, portable. Just a bit long:
- (NSInteger)findValue:(NSString *)value withKey:(NSString *)key
{
    if (!self.dictList)
        return -1;
   
    NSInteger count = 0;
    for (NSDictionary *dict in self.dictList)
    {
        if ([[dict objectForKey:key] isEqualToString:value])
            return count;
        else
            count++;
    }
    return -1;
}
This is what I'm using now. Non-portable iOS-only code, but it's shorter:
- (NSInteger)findValue:(NSString *)value withKey:(NSString *)key
{
    if (!self.dictList)
        return -1;

    NSArray *a = [self.dictList valueForKey:key];
    NSInteger index = [a indexOfObject:value];
    return index == NSNotFound ? -1: index;
}
The annoying first two lines are needed, since this code...
NSArray *a = nil;
NSInteger index = [a indexOfObject:@"test"];
...assings index == 0, which looks like a valid value. Work in progress. Also got to refactor rest of my code to treat NSIntegerMax as "not found" in stead of current "-1" value. More work in progress.

1 comment: