Reputation: 3875
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
Upvotes: 20
Views: 12854
Reputation: 7154
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 . . . . . "
Upvotes: 0
Reputation: 38239
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.
Upvotes: 0
Reputation: 3548
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];
}
Upvotes: 2