【问题标题】:Accessing NSDictionary inside NSArray在 NSArray 中访问 NSDictionary
【发布时间】:2011-02-27 18:16:18
【问题描述】:

我有一个 NSArrayNSDictionary。 数组中的每个字典都有三个键:'Name'、'Sex'和'Age'

如何在NSDictionaryNSArray 中找到索引,例如Name = 'Roger'

【问题讨论】:

    标签: iphone objective-c nsarray nsdictionary


    【解决方案1】:

    在 iOS 4.0 及更高版本上,您可以执行以下操作:

    - (NSUInteger) indexOfObjectWithName: (NSString*) name inArray: (NSArray*) array
    {
        return [array indexOfObjectPassingTest:
            ^BOOL(id dictionary, NSUInteger idx, BOOL *stop) {
                return [[dictionary objectForKey: @"Name"] isEqualToString: name];
        }];
    }
    

    优雅,不是吗?

    【讨论】:

    • 这是我在使用你的函数时得到的——错误:初始化'signed char (^)(struct NSDictionary *, NSUInteger, BOOL *)'的块指针类型不兼容,预期为'BOOL (^) (struct objc_object *, NSUInteger, BOOL *)'
    • 找不到对象会返回什么?
    • @St3fan 您的更正不正确-@Nash 提到的错误是说谓词块返回BOOL,而不是void(正如您通过从块中省略返回类型所暗示的那样声明)。
    【解决方案2】:
        NSUInteger count = [array count];
        for (NSUInteger index = 0; index < count; index++)
        {  
            if ([[[array objectAtIndex: index] objectForKey: @"Name"] isEqualToString: @"Roger"])
            {  
                return index;
            }   
        }
        return NSNotFound;
    

    【讨论】:

    • 数组索引是无符号整数。使用NSUInteger 而不是int
    • else 实际上是一条评论...错别字
    【解决方案3】:

    如果您使用的是 iOS > 3.0,您将能够使用 for in 构造。

    for(NSDictionary *dict in myArray) {
      if([[dict objectForKey:@"Name"] isEqualToString:@"Roger"]) {
        return [myArray indexForObject:dict];
      }
    }
    

    【讨论】:

    • 快速枚举在 iPhone 上一直可用,在 2.x 上也是如此。
    • 这不是很有效,因为您必须在数组上循环两次。首先找到匹配的对象,然后再次找到它的索引。最好使用简单的 for 循环和objectForIndex:,如果您想不使用块。
    【解决方案4】:

    有方法[NSArray indexOfObjectPassingTest]。但它使用了块,这是苹果对 C 的扩展,因此是邪恶的。相反,请这样做:

    NSArray *a; //Comes from somewhere...
    int i;
    for(i=0;i<a.count;i++)
        if([[[a objectAtIndex:i] objectForKey: @"Name"] compare: @"Roger"] == 0)
            return i; //That's the index you're looking for
    return -1; //Not found
    

    【讨论】:

    • 你不应该使用 -1 来表示“未找到”,你应该使用 NSNotFound。使用 isEqualToString: 而不是 compare:... == 0 也会更易读。
    • 既然 Objective-C 也是 C 的扩展,那么块比 Objective-C 更邪恶吗?
    • 投反对票,因为您认为 Blocks 是邪恶的。积木是未来,习惯吧。
    • 另外,使用 NSUInteger 代替 int 来索引数组。
    • @St3fan:未来是垃圾收集语言,而不是 [Objective] C。
    猜你喜欢
    • 1970-01-01
    • 2014-06-13
    • 1970-01-01
    • 1970-01-01
    • 2014-02-24
    • 1970-01-01
    • 1970-01-01
    • 2013-03-10
    • 2011-01-17
    相关资源
    最近更新 更多