Wednesday, November 23, 2011

NSCountedSet (grouping array objects with their total number of counts)

This class gives the count of an object present in an array.

For example: If we have an array named myArray with objects: (AA,HH,TT,SS,AA,KK,TT,TT,XX,HH,HH,HH,SS,SS)

Then to get total no of count of every object only write this code:


 NSCountedSet * set = [[NSCountedSet alloc] initWithArray: myArray];
        for (id obj in set)
        {
            NSLog(@"%d - %@", [set countForObject:obj], obj);
         }

Now you can use this [set countForObject:obj] and obj according to your requirement. 

For example it you want to display this in a table with non-repeated objects and with count you can assign above value in a dictionary like this: 

NSMutableDictionary *dirCount = [[NSMutableDictionary alloc]init];
NSCountedSet * set = [[NSCountedSet alloc] initWithArray:arrForTypeGroup];

        for (id obj in set)
        {
            NSLog(@"%d - %@", [set countForObject:obj], obj);
            [dirCount setObject:[NSNumber numberWithInt:[set countForObject:obj]] forKey:obj];
        }


 NSLog(@"Output: %@", dirCount);

Now use this dictionary to display in table.

Happy Coding :)

1 comment: