在 Objective-C 的 NSMutableDictionary 中更新值或设置新键和值

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

我有一个名字数组,想用 A 和 B 前缀来计算它们。 例如,对于这个用户名,我希望我的 NSMutableDictionary *cellNum 到 return 以每个字母开头的名称计数,例如:"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);
        }
    }
}

尝试使用此代码:

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

这一定会给你想要的结果:{ a = 2; b = 1; }