按字典值返回对象的索引

rso*_*son 3 objective-c

这是我的场景:我有一个包含2个值的字典项数组.

array = (
    {
        id = 1;
        title = "Salon One";
    },
    {
        id = 2;
        title = "Salon Two";
    }
)
Run Code Online (Sandbox Code Playgroud)

我甚至不确定这是否可行,但是我可以将此数组传递给函数并根据字典值返回对象索引吗?

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

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

    return index;
}
Run Code Online (Sandbox Code Playgroud)

Adr*_*ian 10

如果你想使用Snow Leopard中引入的块超级想象,你可以这样做:

- (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];
}
Run Code Online (Sandbox Code Playgroud)

然后每当你想在数组中找到字典的索引时:

[array indexOfObjectPassingTest:[self blockTestingForTitle:@"Salon One"]]
Run Code Online (Sandbox Code Playgroud)


Nik*_*uhe 6

为什么不?

- (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;
}
Run Code Online (Sandbox Code Playgroud)

请注意签名的微小差异(返回类型NSIntegervs int).在64位环境中使用NSNotFound时,这是必需的.

  • 但是,我建议重命名方法`-indexOfObjectInArray:byTitle:`.在Cocoa中使用"get"作为前缀意味着通过引用返回. (2认同)