将数组值添加到NSMutableDictionary

时间:2016-08-08 15:03:36

标签: ios objective-c nsmutabledictionary

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

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得到它。

提前致谢。

2 个答案:

答案 0 :(得分:2)

如果你的数组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"];

答案 1 :(得分:0)

 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"];