Return object index by dictionary value

Here is my scenario: I have a set of dictionary elements with 2 values.

array = (
    {
        id = 1;
        title = "Salon One";
    },
    {
        id = 2;
        title = "Salon Two";
    }
)

I'm not even sure if this is possible, but can I pass this array to a function and return an index of objects based on the value of the dictionary?

- (int)getObjectIndex:(NSMutableArray *)array byName:(NSString *)theName{
    int index;

    /* Pseudo Code*/
    /*index = the index value in 'array' of objectForKey:@"title" = theName*/

    return index;
}
+3
source share
3 answers

Why not?

- (NSInteger)getObjectIndex:(NSMutableArray *)array byName:(NSString *)theName {
    NSInteger idx = 0;
    for (NSDictionary* dict in array) {
        if ([[dict objectForKey:@"title"] isEqualToString:theName])
            return idx;
        ++idx;
    }
    return NSNotFound;
}

Note the slight difference in the signature (return type NSIntegervs int). This is necessary when using NSNotFound in 64-bit environments.

+6
source

If you want to become a super fantasy with the blocks presented in Snow Leopard, you can do:

- (BOOL (^)(id obj, NSUInteger idx, BOOL *stop))blockTestingForTitle:(NSString*)theName {
    return [[^(id obj, NSUInteger idx, BOOL *stop) {
        if ([[obj objectForKey:@"title"] isEqualToString:theName]) {
            *stop = YES;
            return YES;
        }
        return NO;
    } copy] autorelease];
}

and then whenever you want to find a dictionary index in an array:

[array indexOfObjectPassingTest:[self blockTestingForTitle:@"Salon One"]]
+10
source

, , , , .

0

Source: https://habr.com/ru/post/1723672/


All Articles