计算NSArray中的出现次数

时间:2012-06-03 14:18:54

标签: iphone xcode nsarray nspredicate

这是我来自NSArray的代码的一部分:

2012-06-03 16:03:45.140 test[4178:f803] data (
        {
        receiver = david;
        sender = james;
        idMessage = 248;

    },
        {
        receiver = david;
        sender = james;
        idMessage = 247;

    },
        {
        receiver = david;
        sender = Marc;
        idMessage = 246;

    }

)

我想要发件人发送给接收者的消息数量等等

james = 2;
marc = 1;

thx for reading

2 个答案:

答案 0 :(得分:1)

data”是NSArray,似乎包含NSDictionary个对象。

所以你想以这种方式遍历数组:

NSNumber * countOfSender;
NSString * nameOfSender;
NSMutableDictionary * countDictionary = [[NSMutableDictionary alloc] initWithCapacity: 1];

// go through the original array to examine each sender
for(NSDictionary *anEntry in data)
{
    nameOfSender = [anEntry objectForKey: @"sender"];
    if(sender)
    {
       countOfSender = [countDictionary objectForKey: nameOfSender];
        if(countOfSender == NULL)
        {
            // create a new count entry for this particular sender
            countOfSender = [NSNumber numberWithInt: 1];
        } else {
            // increment the previous count
            countOfSender = [NSNumber numberWithInt: [countOfSender intValue] + 1];
        }
        [countDictionary setObject: countOfSender forKey: nameOfSender];
    }
}

// now print out the outputs
for(nameOfSender in [countDictionary allKeys])
{
    countOfSender = [countDictionary objectForKey: nameOfSender];
    NSLog( @"%@ : %d" nameOfSender, [countOfSender intValue] );
}

答案 1 :(得分:0)

你会做类似的事情。

NSMutableArray *array = [NSMutableArray array];
for(id object in yourArray) {

    NSLog("sender:%@ id:%i",[object valueForKey:@"sender"],[[object valueForKey:@"idMessage"] intValue]);

   NSMutableDictionary *dict = [
   NSMutableDictionary dictionary];
   [dict setValue:[object valueForKey:@"sender"] forKey:@"sender"];
   [dict setValue:[NSNumber numberWithInt:[[object valueForKey:@"idMessage"] intValue]] forKey:@"idMessage"];

   [array addObject:dict];
}

NSLog(@"%@",array);