使用特定属性计算NSArray中的项目数(iPhone编程)

时间:2011-03-06 05:03:19

标签: iphone

我有一个看起来像这样的NSArray:

ArrayItem *thisone = [[ArrayItem alloc] initWithName:@"The Name" data1:@"Some data" data2:@"Some more data" image:@"theimage.jpg" range:0];

ArrayItem *thisone1 = [[ArrayItem alloc] initWithName:@"The Name" data1:@"Some data" data2:@"Some more data" image:@"theimage.jpg" range:0];

ArrayItem *thisoneagain = [[ArrayItem alloc] initWithName:@"The Name 2" data1:@"Some data2" data2:@"Some more data2" image:@"theimage2.jpg" range:1];

ArrayItem *thisoneagain1 = [[ArrayItem alloc] initWithName:@"The Name 2" data1:@"Some data2" data2:@"Some more data2" image:@"theimage2.jpg" range:1];

ArrayItem *thisoneagain2 = [[ArrayItem alloc] initWithName:@"The Name 2" data1:@"Some data2" data2:@"Some more data2" image:@"theimage2.jpg" range:1];

ArrayItem *thisoneyetagain = [[ArrayItem alloc] initWithName:@"The Name 3" data1:@"Some data3" data2:@"Some more data3" image:@"theimage3.jpg" range:2];

ArrayItem *thisoneyetagain1 = [[ArrayItem alloc] initWithName:@"The Name 3" data1:@"Some data3" data2:@"Some more data3" image:@"theimage3.jpg" range:2];

ArrayItem *thisoneyetagain2 = [[ArrayItem alloc] initWithName:@"The Name 3" data1:@"Some data3" data2:@"Some more data3" image:@"theimage3.jpg" range:2];

ArrayItem *thisoneyetagain3 = [[ArrayItem alloc] initWithName:@"The Name 3" data1:@"Some data3" data2:@"Some more data3" image:@"theimage3.jpg" range:2];

self.ArrayItems = [[NSMutableArray alloc] initWithObjects:thisone,thisone1,thisoneagain,thisoneagain1,thisoneagain2,thisoneyetagain,thisoneyetagain1,thisoneyetagain2,thisoneyetagain3,nil];

我想计算每个“范围”中的项目数量(如有2个项目,范围为0,3个范围为1,4个范围为2)并存储数量每个范围的项目在单独的变量中。知道怎么做吗? ArrayItems.count只告诉我总共有多少。

3 个答案:

答案 0 :(得分:1)

你可以使用块来实现,从iOS 4开始:

NSIndexSet *range0Indexes = [self.ArrayItems indexesOfObjectsPassingTest:(BOOL)^(id obj, NSUInteger idx, BOOL *stop) {
   return ((ArrayItem *)obj).range == 0;
}];

NSUInteger countRange0 = [range0Indexes count];

do same for range1 and range2.

答案 1 :(得分:0)

使用循环:

NSUInteger counts[3] = {0,0,0};
for(ArrayItem * item in self.ArrayItems) {
    counts[item.range]++;
}

然后counts[i]包含数组中包含范围i的项目数。 (这大大有助于你的范围从零开始,并且(可能是)整数。)

答案 2 :(得分:0)

这更像是一般编程问题,而不是iOS特定问题,但我会使用Objective-C给出答案。

创建阵列后,您可以执行以下操作:

int range0=0;
int range1=0;
int range2=0;    
for (ArrayItem* item in self.ArrayItems) {
//Assuming range is an int property of ArrayItem we can switch on it.
    switch (item.range) {
        case 0:
            range0++;
            break;
        case 1:
            range2++;
            break;
        case 2:
            range3++
            break;
        default:
            break;
    }
}

这将为您提供存储在range0,range1和range2变量上的每个范围的项目数。

使用蒂姆的方法你可以这样做:

NSUInteger counts[3] = {0,0,0};
for(ArrayItem * item in self.ArrayItems) {
    counts[item.range]++;
}