如何从两个Mutablearrays中检索值并将它们存储在MutableDictionary中,并将键作为数组存储?

时间:2013-09-14 06:06:29

标签: ios objective-c arrays nsmutabledictionary

我有3个NSMutableArrays k,名称,数字

k数组包含 {a,b,c,d,e,.....}

名字数组包含 {apple,bag,banana,car,cat,dall,elephant,.....}

数字数组包含 {100,200,300,400,500,600,700,...}

这里所有3个阵列都是动态的。

我想将名字[],数字[]添加到 NSMutableDictionary ,其中k []为关键数组..

当我输入字典

时,我的输出应该是这样的

apple 100

B'/ P>

bag 200

banana 300

C

汽车400

cat 500

d

dall 600

ë

elephant 700

有人可以帮助我吗? 谢谢。

3 个答案:

答案 0 :(得分:0)

NSMutableDictionary *result = [NSMutableDictionary new];
for(int i = 0; i<k.count; i++){
    unichar letter = [k objectAtIndex:i]; //I'm assuming you have chars in your k array,            
                                           // if not, you have to format it here
    NSString* name = [names objectAtIndex:i];
    if([[name characterAtIndex:0] isEqual:letter]){
        NSString *objectToInsert = [NSString stringWithFormat:@"%@: %@", @"name", [numbers objectAtIndex:i]];
        [result setObject:objectToInsert forKey:letter];
    }
}

你可以更多地优化它,但它应该工作;)

答案 1 :(得分:0)

尝试使用以下代码

NSMutableDictionary *mydic = [[NSMutableDictionary alloc] init];

For(int k = 0; k < firstArray.count ; k++)
{
  NSPredicate *pred =[NSPredicate predicateWithFormat:@"SELF beginswith[c] %@", [firstArray objectAtIndex:k]];
  NSArray *filteredArr = [MySecodArray filteredArrayUsingPredicate:pred];

  NSString *myString = @"";
  for (int t = 0 ; t < filteredArr.count ; t ++)
  {
    myString = [MyThirdArray objectAtIndex:[MySecodArray indexOfObject:[filteredArr  objectAtIndex:t]]];
    myString = [[filteredArr  objectAtIndex:t] stringByAppendingString:myString];
    [mydic setValue: myString forKey:[firstArray objectAtIndex:k]];

    myString = @"";   
  }
}
NSLog(@"%@", myDic);

答案 2 :(得分:0)

你可以这样做,我假设nameArry和NumberArray计数相同 - &gt;

尝试此代码

NSSMutableDictionary *finalDictionary = [[NSSmutableDictionary alloc]init];
for(int i=0;i<k.count;i++)
{
   NSString *alphaBet = [k objectAtIndex:i];

   //initialize array here 

   NSMutableArray *insideDictArray = [[NSMutableArray alloc]init];

   for(int j=0;j<nameArray.count;j++)
   {
     NSString *name = [nameArray objectAtIndex:j];
     if([name hasPreffix:alphabet])
     {
       //get Number String

       NSString *numberForName = [numberArray objectAtIndex:j];

       //Now Concate Number and Name

       NSString *concateString = [name stringByAppendingFormat:@"
       %@",numberForName]; 

       //Put this in Array we just intialized outside of secondLoop

      [insideDictArray addObject:concateString];        
     }
   }
   //Now Add array to finalDictionary

   [finalDictionary addObject:insideDictArray forKey:alphabet];
}

OutPut将是这样的我希望:

finalDictionary = 
{
a = [aple 100];
b = [bag 200,banana 300];
.
.
}