Search code examples
iosobjective-cnsmutabledictionary

Update value or Set new key & value in NSMutableDictionary in Objective-C


I have an array of names and want to count them by having A & B prefix. For example for this username I want my NSMutableDictionary *cellNum to return the count of names starting with each alphabet, like: "A":"2" & "B":"1".

@interface ...
{
    NSArray *users;
    NSMutableDictionary *cellNum;
}

@implementation ...
{
    users = @[@"Ali",@"Armita",@"Babak"];

    for (int i=0;i<users.count;i++)
    {
        if ( [users[i] hasPrefix:@"A"] )
        {
            cellNum[@"a"] = @([cellNum[@"a"] intValue]+1);
        }
        else
        {
            cellNum[@"b"] = @([cellNum[@"b"] intValue]+1);
        }
    }
}

Solution

  • Try using this code:

    NSMutableDictionary *cellNum = [NSMutableDictionary dictionary];
      
    [cellNum setObject:@(0) forKey:@"a"];
    [cellNum setObject:@(0) forKey:@"b"];
      
    NSArray* users = @[@"Ali",@"Armita",@"Babak"];
      
    for (int i=0;i<users.count;i++)
    {
        if ( [users[i] hasPrefix:@"A"] ) {
            cellNum[@"a"] = @([cellNum[@"a"] intValue]+1);
        } else {
            cellNum[@"b"] = @([cellNum[@"b"] intValue]+1);
        }
    }
    

    This will surely Give you the desired result: { a = 2; b = 1; }