簡體   English   中英

如何在 NSDictionary 中為鍵和對象添加數組

[英]How to add arrays for key and object in NSDictionary

我有 2 個數組。 數組 A arrayA[0] 包含 {a,b,c,d,e...},數組 B arrayB[0] 包含 {a,b,c...}。 並且這兩個數組都是可變的並且有很多對象。 NSMutableDictionary中,數組 A 中的每個元素(作為鍵)應該存儲整個數組 B。

例如:

(鍵值)數組 A[0] 具有整個(對象值)數組 B(0...200)

(鍵值)數組 A[1] 具有整個(對象值)數組 B(0...200)

(鍵值)數組 A[2] 具有整個(對象值)數組 B(0...200)

我的代碼:

for (int i=0; i<100; i++)
{

    [someDictionary setObject:arrayB forKey:arrayA[i]];

}

這不起作用,我也試過這個:

[someDictionary initWithObjects:arrayB forKeys:arrayA[i]]

您應該使用NSString將鍵存儲在鍵值對中。 所以我會推薦

for (int i=0; i<100; i++) {

    NSString *str=(NSString *)arrayA[i];

    [someDictionary setObject:arrayB forKey:str];

}

您的代碼原則上看起來不錯。 顯然固定為 100 個元素並不好,所以我會寫

for (id key in self.arrayA)
    [someDictionary setObject:self.arrayB forKey:key];

試試這個答案。 我不知道兄弟我是否正確或錯誤地理解了你的問題。

試試我的代碼:

NSMutableArray *tempA=[NSMutableArray array];
NSMutableArray *tempB=[NSMutableArray array];

for (int a = 0; a < 100; a++)
{
     [tempA addObject:[NSString stringWithFormat:@"%d",a]];
}

NSMutableArray *dataArray=[NSMutableArray array];
NSMutableDictionary *dict;

for (int i = 0; i < [tempA count]; i++)
{
        for (int a = 0; a < 100; a++)
        {
            dict=[NSMutableDictionary dictionary];
            NSString*  localTemp=[NSString stringWithFormat:@"key-%@",[tempA objectAtIndex:i]];
            [tempB addObject:[NSString stringWithFormat:@"%d",a]];
            id object=[tempB objectAtIndex:a];
            [dict setObject:object forKey:localTemp];
            [dataArray addObject:dict];
        }
    }
    NSLog(@"Dictionary is---->%@",dataArray);
 NSArray *arrayA = [NSArray arrayWithObjects:@"1",@"2", nil];
    NSArray *arrayB = [NSArray arrayWithObjects:@"3",@"4", nil];
    NSMutableDictionary *temp = [[NSMutableDictionary alloc]init];

    for(int i =0 ; i<[arrayA count];i++)
    {
        [temp setObject:arrayB forKey:[arrayA objectAtIndex:i]];
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM