1

我有 3 个 NSMutableArrays k,names,numbers

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

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

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

所有 3 个数组在这里都是动态的。

我想以k[] 作为键数组将 names[],numbers[] 添加到NSMutableDictionary ..

当我品脱那本字典时,我的输出应该是这样的

一个

苹果 100

b

袋子 200

香蕉 300

C

车400

猫 500

d

达尔 600

e

大象 700

有人可以帮助我。谢谢你。

4

3 回答 3

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

您可能可以对此进行更多优化,但它应该可以工作;)

于 2013-09-14T06:21:22.183 回答
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);
于 2013-09-14T06:31:13.153 回答
0

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

试试这段代码

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

我希望输出会是这样:

finalDictionary = 
{
a = [aple 100];
b = [bag 200,banana 300];
.
.
}
于 2013-09-14T06:45:11.833 回答