0

我有一部分代码返回 numberOfRowsInSection。

代码

for (NSDictionary *consoleDictionary in [self arrayFromJSON]) {
    if ([[consoleDictionary objectForKey:@"model"] isEqualToString:@"PlayStation 3"]) {
        NSLog(@"%@", consoleDictionary);
    }
}

输出

2013-02-03 22:37:08.468 PageControl01[5782:c07] {
    console = PlayStation;
    game = "007 Legends";
    id = 1;
    model = "PlayStation 3";
    publisher = "Electronic Arts";
}
2013-02-03 22:37:08.478 PageControl01[5782:c07] {
    console = PlayStation;
    game = "Ace Combat: Assault Horizon";
    id = 2;
    model = "PlayStation 3";
    publisher = Namco;
}

这显然是正确的,因为它记录了所有"PlayStation 3"模型。然而,这不是我需要的。我想记录"PlayStation 3"'s 的数量。所以我稍微调整一下代码,然后:

for (NSDictionary *consoleDictionary in [self arrayFromJSON]) {
    if ([[consoleDictionary objectForKey:@"model"] isEqualToString:@"PlayStation 3"]) {
        NSLog(@"%d", [consoleDictionary count]);
    }
}

输出

2013-02-03 22:39:43.605 PageControl01[5816:c07] 5
2013-02-03 22:39:43.605 PageControl01[5816:c07] 5

这一个非常接近但又如此接近。而不是记录数字5,它应该记录数字,2因为只有2 "PlayStation 3".

请帮忙。

4

3 回答 3

2

您不需要显式循环遍历数组。

NSIndexSet *is = [array indexesOfObjectsPassingTest:^(id obj, NSUInteger idx, BOOL *stop) {
    return [[obj objectForKey:@"model"] isEqualToString:@"PlayStation 3"];
}];
int numOfPS3s = is.count;
于 2013-02-03T15:25:42.730 回答
1
  1. 它正在记录数字 5,因为您的每个字典中有 5 个键(consolegameidmodelpublisher)。如果不是每次[consoleDictionary count]只向计数器添加一个而不是记录,那么int最后您将在计数器中获得预期的结果。

  2. 你可以获取对象的数量是一个更简单的方法:[self arrayFromJSON]是一个数组

通常:

NSInteger nbPS3 = [[self arrayFromJSON] indexesOfObjectsPassingTest:^(id obj, NSUInteger idx, BOOL *stop) {
  return [obj[@"model"] isEqualToString:@"PlayStation 3"];
}].count
于 2013-02-03T15:31:47.327 回答
1

是的,count总是总计数,而不是索引,而不是匹配计数。对于这个特定问题,使用indexesOfObjectsPassingTest是最直接的解决方案,但如果您对其他用于迭代结果集的技术感兴趣,而且不仅要跟踪对象,还要跟踪索引,请考虑这两种方法:

for (NSInteger i = 0; i < [self.arrayFromJSON count]; i++) {
    if ([[[self.arrayFromJSON objectAtIndex:i] objectForKey:@"model"] isEqualToString:@"PlayStation 3"]) {
        NSLog(@"%d", i);
    }
}

或者

[self.arrayFromJSON enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
    if ([[obj objectForKey:@"model"] isEqualToString:@"PlayStation 3"]) {
        NSLog(@"%d", idx);
    }
}];

Obviously, if you're looking for how many records match, you'd just increment your own counter, rather than logging the index for each match.

于 2013-02-03T15:35:20.607 回答