简体   繁体   中英

count occurrences in a NSArray

this is a part of my code from a 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;

    }

)

I want the number of messages sent by sender to receiver or something like that

james = 2;
marc = 1;

" data " is the NSArray, which appears to contain NSDictionary objects.

So you'd want to loop through the array this way:

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

You would do something like..

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM