0

I have an array with 5 sub arrays that I'm trying to loop through, I can access the first sub array and its objects but when I increase the variable count and try to access the second sub array my program crashes any ideas on a better way to do this? This is the my general method:

-(void) accessArray {
    NSArray *myArray; // my array that holds sub arrays  
    int count = 0; //used to hold which sub array im accesing  
    NSArray *subArray = [myArray objectAtIndex:count];
    //do something with object   =  [subArray objectAtIndex:0];
    //do something with object    = [subArray objectAtIndex:1];
}

-(void) otherMethod {
    count ++

    [self accessArray]; 

}
2
  • 1
    where are you looping in this code? Commented Aug 26, 2011 at 7:07
  • new to programming, i thought using count++ would be consider a way to loop through my array - correction noted Commented Aug 26, 2011 at 7:19

3 Answers 3

2
for (NSArray *inner in outerArray)
    for (id object in inner) {
        ... do stuff ...
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

for (NSSArray *subArray in myArray)
0

In addition to bbums answer you can make sub arrays using NSRange (example from NSArray Class Reference):

NSArray *halfArray;

NSRange theRange;



theRange.location = 0;

theRange.length = [wholeArray count] / 2;



halfArray = [wholeArray subarrayWithRange:theRange];

Only saying this because it looks like this might be what you are trying to do. This doesn't iterate through objects, but it is handy when trying to make new arrays from others.

Comments

0

If you REALLY want to do it using your way (i.e. access the subarrays through 'otherMethod'), you'll need to make the 'count' variable accessible to both methods:

int count = 0; // used to hold which sub array I'm accessing

-(void) accessArray {
    NSArray *myArray; // my array that holds sub arrays
    NSArray *subArray = [myArray objectAtIndex:count];
    // do something with object = [subArray objectAtIndex:0];
    // do something with object = [subArray objectAtIndex:1];
}

-(void) otherMethod {
   count++;             // Cannot access count if defined inside 'accessArray'
   [self accessArray]; 
}

Now you can use 'otherMethod' to access the subarrays. But I think the best way to do this is already given in the first answer above by bbum.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.