将数组值添加到 NSMutableDictionary

Add Array values to NSMutableDictionary

我运行遇到了一个问题,我找不到解决它的方法。基本上我需要制作一个带有一些值的可变字典。所有值都是动态的,我从网络服务或其他变量中获取它们。

NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
    [dict setObject:comment.text forKey:@"Comment"];
    [dict setObject:name.text forKey:@"Name"];
    [dict setObject:[NSString stringWithFormat:@"%d",isPublic] forKey:@"VisibleForAll"];
po dict
{
    Comment = "no comment";
    Name = "test";
    VisibleForAll = 1;
    -> carts
}

此外,我想将以下树添加到我的字典中,但我不知道该怎么做。

我在 2 NSArray artIDqty 中有必要的项目,但我不知道如何创建底部,所以我可以将它添加到 dict.

Carts {
       Cart {   
             ArticleID : 22
             Quantity : 1
            }
       Cart {   
             ArticleID : 45
             Quantity : 3
            }
       ...
      }

我会用 [dict setObject:carts forKey:@"Cart"] 添加它,但我不知道如何添加值,所以我将 dictionary 放在我给你的表格上。

此外,不要忘记数字或 Carts 是灵活的。我将从 Product.count 获取它。

提前致谢。

如果您的数组 artIDqty 在创建字典的相同索引处都有值,您可以这样尝试

NSMutableArray *carts = [[NSMutableArray alloc] init];
for(NSInteger i=0; i<products.count; i++) {
    //If you have custom class `cart` than use that
    Cart *cart = [[Cart alloc] init];
    cart.ArticleID = [[products objectAtIndex:i] valueForKey:@"pid"];
    cart.Quantity = [[products objectAtIndex:i] valueForKey:@"qty"];

    //If you not have any custom class than use Dictionary
    NSMutableDictionary *cart = [[NSMutableDictionary alloc] init];
    [cart setObject:[[products objectAtIndex:i] valueForKey:@"pid"] forKey:@"ArticleID"];
    [cart setObject:[[products objectAtIndex:i] valueForKey:@"pid"] forKey:@"Quantity"];
}

现在使用键

将此 carts 数组添加到 Dictionary
[dict setObject:carts forKey:@"carts"];
 NSArray *pid = [products valueForKey:@"pid" ];
    NSArray *qty = [products valueForKey:@"qty"];

    NSMutableArray *carts = [[NSMutableArray alloc] initWithCapacity:products.count];



    for(NSInteger i=0; i<products.count; i++) {
        NSMutableDictionary *cart = [[NSMutableDictionary alloc] init];
        NSMutableDictionary *cartemp = [[NSMutableDictionary alloc] init];

        [cart setObject:[pid objectAtIndex:i] forKey:@"ArticleId"];
        [cart setObject:[qty objectAtIndex:i] forKey:@"Quantity"];
        [cartemp setObject:cart forKey:@"Cart"];
        [carts addObject:cartemp];
    }

    [dict setObject:carts forKey: @"Carts"];