2014-01-08 37 views
0

使用循环多维数组我想为iOS平台像下面的PHP语法创建数组,非常感谢~~如何创建IOS的Xcode

$createArray = array(); 

    for ($i = 0; $i<10; $i++) { 

    $createArray[$i]['name'] = $name; 
    $createArray[$i]['age'] = $age; 
    } 
+0

考虑使用的NSDictionary比这更好2维阵列。让我知道你是否需要关于NSDictionary的信息 –

回答

7

尽量保存自己的价值观NSDictionary中,并添加字典到你的阵列

NSMutableArray *theArray = [NSMutableArray array]; 

    for (int indexValue = 0; indexValue<10; indexValue++) { 
     NSMutableDictionary *theDictionary = [[NSMutableDictionary alloc] init]; 
     [theDictionary setObject:name forKey:@"name"]; 
     [theDictionary setObject:age forKey:@"age"]; 
     [theArray addObject:theDictionary] 
    } 

在检索时间,

NSString *name = [[theArray objectAtIndex:indexValue] objectForKey:@"name"]; 
NSString *age = [[theArray objectAtIndex:indexValue] objectForKey:@"age"]; 
0

试试这个。

array = [[NSMutableArray alloc] init]; 

    for (int i = 0; i < 10; i++) { 
     NSMutableArray *subArray = [[NSMutableArray alloc] init]; 
     for (int j = 0; j < 2; j++) { 
    //Do your Stuff 
      // [subArray addObject:name]; 
      // [subArray addObject:Age]; 
     } 
     [array addObject:subArray]; 

    } 

OR

为什么不能用NSDictionary

0

您可以使用它。但这在IOS中不是更好的方式。

NSMutableArray *array[20]; 
    for (int i=0;i< 20; i++) 
    { 
     array[i] = [NSMutableArray array]; 
     for (int j=0;j<3;j++) 
     { 
      NSMutableDictionary *theDictionary = [[NSMutableDictionary alloc] init]; 
      [theDictionary setObject:name forKey:@"name"]; 
      [theDictionary setObject:age forKey:@"age"]; 
      [[array[i] addObject:theDictionary] 
     } 
    } 
2

,你可能会发现:

array = [[NSMutableArray alloc] init]; 

for (int i = 0; i < 8; i++) { 
    NSMutableArray *subArray = [[NSMutableArray alloc] init]; 
    for (int j = 0; j < 8; j++) { 
     [subArray addObject:[NSNumber numberWithInt:0]]; 
    } 
    [array addObject:subArray]; 
    [subArray release]; 
} 

还要检查this question

0

首先你已经设置一个NSMutableDictionary上的.h文件

 @interface MSRCommonLogic : NSObject 
     { 
      NSMutableDictionary *twoDimensionArray; 
     } 

     then have to use following functions in .m file 


     - (void)setValuesToArray :(int)rows cols:(int) col value:(id)value 
     { 
      if(!twoDimensionArray) 
      { 
       twoDimensionArray =[[NSMutableDictionary alloc]init]; 
      } 

      NSString *strKey=[NSString stringWithFormat:@"%dVs%d",rows,col]; 
      [twoDimensionArray setObject:value forKey:strKey]; 

     } 

     - (id)getValueFromArray :(int)rows cols:(int) col 
     { 
      NSString *strKey=[NSString stringWithFormat:@"%dVs%d",rows,col]; 
      return [twoDimensionArray valueForKey:strKey]; 
     }