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
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 ).
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.
arrays can't contain nil.
if (array.count > 4) {
sections = [array objectAtIndex:4];
}
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];
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With