Sunday, June 16, 2013

NSCountedSet addObject example in Objective C (iOS).

NSCountedSet addObject

Adds a given object to the set.

- (void)addObject:(id)anObject

The object to add to the set.

Discussion of [NSCountedSet addObject]
If anObject is already a member, addObject: increments the count associated with the object. If anObject is not already a member, it is sent a retain message.

NSCountedSet addObject example.
countedList = [[NSCountedSet alloc] initWithArray:listOfItems];//listOfItems is an array of country name strings with duplicates
    listOfItems2 = [NSMutableArray array]; // array without duplicates that's the data source for the UITableView

    for (NSString *aCountry in countedList) {
        NSMutableDictionary *dict = [NSMutableDictionary dictionary];
        [dict setValue:aCountry forKey:@"name"];
        [dict setValue:[NSString stringWithFormat:@"%lu",[countedList countForObject:aCountry]] forKey:@"count"];
        [listOfItems2 addObject:dict];

Example of [NSCountedSet addObject].
    NSArray *arr = @[@1, @3, @4, @6, @6, @3, @1, @3];
    NSCountedSet *totalSet = [NSCountedSet setWithArray:arr];
    NSMutableArray *dictArray = [NSMutableArray array];
    for (NSNumber *num in totalSet) {
        NSDictionary *dict = @{@"number":num, @"count":@([totalSet countForObject:num])};
        [dictArray addObject:dict];
    NSArray *final = [dictArray sortedArrayUsingDescriptors:@[[NSSortDescriptor sortDescriptorWithKey:@"number" ascending:YES ]]];

NSCountedSet addObject example.
@interface NSCountedSet (JRCountedSetAdditions)

- (NSArray *) objectsWithCount:(NSUInteger) count;


@implementation NSCountedSet (JRCountedSetAdditions)

- (NSArray *) objectsWithCount:(NSUInteger) count {
   NSMutableArray *array = [NSMutableArray array];
   for(id obj in self) {
      if([self countForObject:obj] == count) {
        [array addObject:obj];
   return [array copy];


End of NSCountedSet addObject example article.