Search code examples
iosobjective-cuiscrollviewnsarraynsrangeexception

Looping through an array, index error


I am creating a UIScrollView that scrolls sideways and has a number of buttons and labels (that go with the buttons) that I am adding programmatically.

I have 44 buttons and labels, so I want to create them through an array.

This is how I am trying to do it (I'm a newish programmer so I know for a fact its the wrong way to do it.

Keep in mind, nameArray holds strings for the labels and the picArray holds strings for the filenames for pictures.

Anyways, this is in my viewDidLoad::

for (int i = 0; i < 44; i++) {
    NSIndexPath *path = [nameArray objectAtIndex:i];
    [self makeLabelsAndButtons:path];
    //NSLog(@"index path is:%@", path);
}

The method that this for loop is referencing is written below:

-(void)makeLabelsAndButtons:(NSIndexPath*)indexPath{
NSString *nameString = [nameArray objectAtIndex:indexPath];
NSString *picString = [picArray objectAtIndex:indexPath];

NSLog(@"name: %@, pic:%@", nameString, picString);

}

There is not much in the makeLabelsAndButtons method because I am trying to get the concept down before adding the meat of the code.

This is the error I crash with:

*** Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[__NSArrayI objectAtIndex:]: index 54564 beyond bounds [0 .. 43]

I know that this means the array is out of the bounds but I have no idea why.

Any help is appreciated!


Solution

  • If nameArray holds strings for the labels, then path is not an NSIndexPath, it's a string. So you're passing a string to objectAtIndex: which, of course wants an integer not a string.

    Even if it were an NSIndexPath, your code would still be wrong because you want an integer not an index path to pass to objectAtIndex.

    I think what you want to do is just pass i to your makeLabelsAndButtons method.

    for (int i = 0; i < 44; i++) {
        [self makeLabelsAndButtons:i];
        //NSLog(@"index path is:%@", path);
    }
    
    -(void)makeLabelsAndButtons:(NSInteger)index{
        NSString *nameString = [nameArray objectAtIndex:index];
        NSString *picString = [picArray objectAtIndex:index];
    
        NSLog(@"name: %@, pic:%@", nameString, picString);
    }