Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSArray out of bounds check

Tags:

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

like image 305
spacebiker Avatar asked Mar 15 '12 07:03

spacebiker


People also ask

How do you check out of bound?

Simply use: boolean inBounds = (index >= 0) && (index < array. length); Implementing the approach with try-catch would entail catching an ArrayIndexOutOfBoundsException , which is an unchecked exception (i.e. a subclass of RuntimeException ).

How do you check if an array index is out of bounds?

The getOrNull() function returns an element at the given index, or null if the index is out of bounds of the array. It can be used as follows to determine if an index is valid or not.

Can NSArray contain nil?

arrays can't contain nil.


2 Answers

if (array.count > 4) {
    sections = [array objectAtIndex:4];
}
like image 161
sch Avatar answered Oct 19 '22 08:10

sch


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];
}
like image 34
dplusm Avatar answered Oct 19 '22 10:10

dplusm