NSArray out of bounds check

旧时模样 提交于 2019-12-22 01:36: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


回答1:


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



回答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];
}



回答3:


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.




回答4:


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



来源:https://stackoverflow.com/questions/9715261/nsarray-out-of-bounds-check

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!