开发者

trying to loop through nested array , obj-c

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 an开发者_高级运维y 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]; 

}


for (NSArray *inner in outerArray)
    for (id object in inner) {
        ... do stuff ...
    }
}


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜