Zee
Zee

Reputation: 172

objective-c accessing arrays

I have done the following trying to create 2d and 3d arrays:

Array1 = [[NSMutableArray alloc]init];
Array2 = [[NSMutableArray alloc]init];
Array3 = [[NSMutableArray alloc]init];

for loop 
[Array1 insertObject:Array2 atIndex:i];
//some code....
[Array2 insertObject:Array3 atIndex:j];

im not sure if this is right but every time i loop in my code i add Array2 to a new index in Array1 but im note sure if this works. In other words i hope im not moving the whole array again every time ?!!

Now my problem is that i need to access array2 through looping in array1, then array3 through array2. I just need to know how to access these arrays using loops so that i can display each array's contents. I need to do something like this array [i][j] where "i" for array1 and "j" is for array2

Upvotes: 2

Views: 6495

Answers (3)

visakh7
visakh7

Reputation: 26400

I am not sure if i understand you properly but if you want to access an array within an array you can use

    [[array1 objectAtIndex:i] objectAtIndex:j];

Pls go through this SO question How to create Array of Array in iPhone?

Is something like this what you need?

UPDATE

NSMutableArray *array1 = [NSMutableArray arrayWithObjects:@"A",@"B",@"C",nil];
NSMutableArray *array2 = [NSMutableArray arrayWithObjects:@"1",@"2",@"3",nil];
NSMutableArray *array3 = [[[NSMutableArray alloc] init] autorelease];
[array3 addObject:array2];
[array3 addObject:array1];
for(int i = 0; i < [array3 count]; i++)
  for(int j = 0; j<[array1 count]; j++)
    NSLog(@"From array3 %@",[[array3 objectAtIndex:i] objectAtIndex:j]);

Upvotes: 0

5hrp
5hrp

Reputation: 2230

Create 3d-array (NxMxP):

NSMutableArray *array3D = [[NSMutableArray alloc] initWithCapacity:N];

for (int i = 0; i < N; ++i)
{
    NSMutableArray *array2D = [[NSMutableArray alloc] initWithCapacity:M];
    for (int i = 0; i < M; ++i)
    {
        NSMutableArray *justAnArray = [[NSMutableArray alloc] initWithCapacity:P];
        [array2D addObject:justAnArray];
        [justAnArray release];
    }
    [array3D addObject:array2D];
    [array2D release];
}

Use this creature:

[[[array3D objectAtIndex:3] objectAtIndex:4] objectAtIndex:1]; // it's like array3D[3][4][1]

Upvotes: 3

Inder Kumar Rathore
Inder Kumar Rathore

Reputation: 40018

Just writing what I have understood...
for accessin the array in loop do
for loop

 NSArray arr = [Array1 objectAtIndex:i] objectIndex:j]; 


will give the the arr[i][j];

Upvotes: 0

Related Questions