Search code examples
iosiphoneobjective-cxcodeios7

How to create a Multidimensional Array using loop in IOS xcode


I would like to create an array for iOS platform like the PHP syntax below, many thanks ~~

$createArray = array ();

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

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

Solution

  • Save your values in NSDictionary and add that dictionary into your array

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

    While Retrieving time,

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