2016-08-08 87 views
-1

我遇到了一個問題,我無法找到克服它的方法。基本上我需要製作一些有價值的可變字典。所有的值都是動態的,我從Web服務或其他變量中獲取它們。添加數組值到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 NSArrayartIDqty必要的項目,但我不知道如何創建底部,所以我可以將它添加到dict

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

我將與[dict setObject:carts forKey:@"Cart"]添加它,但我不知道如何以這樣的方式,我會讓我的dictionary我介紹你在窗體上添加值。

此外,不要忘記,數字或Carts是靈活的。我會從Product.count得到它。

在此先感謝。

回答

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

您的回答部分正確,但它幫助我達成了解決方案。 –

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"]; 
相關問題