2009-11-23 36 views
3

这是我的场景: 我有一个包含2个值的字典项目数组。按字典值返回对象的索引

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

我什至不知道这是否可能,但我可以传递这个数组到一个函数并返回一个基于字典值的对象索引?

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

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

    return index; 
} 

回答

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; 
} 

注意在签名(返回类型NSInteger VS int)略有差异。在64位环境中使用NSNotFound时这是必需的。

+0

+1击败我10秒! – 2009-11-23 15:41:59

+2

但是,我建议重命名方法'-indexOfObjectInArray:byTitle:'代替。在Cocoa中使用“get”作为前缀意味着通过引用返回。 – 2009-11-23 15:43:00

+0

@奎因:绝对,谢谢你指出。 – 2009-11-23 15:46:30

0

当然,这是可能的,只是通过数组,直到你找到循环您正在寻找

10

如果你想要去的超幻想与雪豹推出块,你可以这样做:

- (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]; 
} 

,然后只要你想找到一本字典的数组索引:

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

这个策略比枚举数组更好,因为它使NSArray有机会并行运行。 – 2010-05-22 04:28:25

+0

上述代码是否可以在iPhone 3.x操作系统中使用? – Satyam 2011-02-09 12:56:07