20

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

spacebiker
  • 3,777
  • 4
  • 30
  • 49

4 Answers4

18
if (array.count > 4) {
    sections = [array objectAtIndex:4];
}
sch
  • 27,436
  • 3
  • 68
  • 83
  • 1
    Damn.. im so stupid.. of course!! an array gets filled sequentially. i made my head a mess. Thanks mate +1 – spacebiker Mar 15 '12 at 07:19
  • 4
    I think objective-c language is a little bit stupid here. I would be more comfortable with if `[array objectAtIndex:outOfBounds]` returned `nil` instead of crashing. – turingtested May 24 '16 at 10:20
2

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];
}
dplusm
  • 3,548
  • 2
  • 14
  • 6
0

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.

Paresh Navadiya
  • 38,095
  • 11
  • 81
  • 132
0

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 . . . . . "

turingtested
  • 6,356
  • 7
  • 32
  • 47