Question

noobie question.. What is the best way to check if the index of an NSArray or NSMutableArray exists. I search everywhere to no avail!!

This is what I have tried:

if (sections = [arr objectAtIndex:4])
{
    /*.....*/
}

or

sections = [arr objectAtIndex:4]
if (sections == nil)
{
    /*.....*/
}

but both throws an "out of bounds" error not allowing me to continue

(do not reply with a try catch because thats not a solution for me)

Thanks in advance

Was it helpful?

Solution

if (array.count > 4) {
    sections = [array objectAtIndex:4];
}

OTHER TIPS

If you have an integer index (e.g. i), you can generally prevent this error by checking the arrays bounds like this

int indexForObjectInArray = 4;
NSArray yourArray = ...

if (indexForObjectInArray < [yourArray count])
{
    id objectOfArray = [yourArray objectAtIndex:indexForObjectInArray];
}

Keep in mind NSArray is in sequential order from 0 to N-1 items

Your are trying to access item which has exceeded limit and a array is nil then compiler would throw out of bound error.

EDIT : @sch's answer above shows how can we check if NSArray has required ordered item present in it or not.

You can use the MIN operator to fail silently like this [array objectAtIndex:MIN(i, array.count-1)], to either get next object in the array or the last. Can be useful when you for example want to concatenate strings:

NSArray *array = @[@"Some", @"random", @"array", @"of", @"strings", @"."];
NSString *concatenatedString = @"";
for (NSUInteger i=0; i<10; i++) {  //this would normally lead to crash
    NSString *nextString = [[array objectAtIndex:MIN(i, array.count-1)]stringByAppendingString:@" "];
    concatenatedString = [concatenatedString stringByAppendingString:nextString];
    }
NSLog(@"%@", concatenatedString);

Result: "Some random array of strings . . . . . "

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top