new2ios
new2ios

Reputation: 1350

How to use [for] to list all elements in 2 dimensional NSArray?

I need to make calculation on 2 dimensional NSArray. I don't figure out how to scroll through NSArray. As I understand NSArray is only 1 dimensional. So I suppose that have to scroll through rows and convert each row to NSArray again. And from it extract elements with index of column inside. I can not figure out how to use for to complete that operation.

My code is below

for (id object in myArray) {
    if([object[6] intValue] == 1){
        sumAmount += [object[3] intValue];
    }
}

Upvotes: 0

Views: 47

Answers (2)

Caleb
Caleb

Reputation: 125017

A "two dimensional" array is just an array of arrays, so you nest your for loops like this:

for (NSArray *row in myArray) {
    for (id object in row) {
        // do something with object, such as...
        sumAmount += [object intValue];
    }
}

Upvotes: 2

Greg
Greg

Reputation: 25459

You can use two for loop like this:

for(int row = 0; row < NUM_OF_ROWS; row++) {
    for (int col = 0; col < NUM_OF_COL; col++){
        element = myArray[row][col];
    }
}

Just convert the code to match your data structure.

Upvotes: 0

Related Questions