Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Testing for contents of an NSArray without risking range error

I'm foolishly saying:

if ([imageCache objectAtIndex:index]) {

Problem is, on my first time through this, I haven't put ANYTHING in my NSMutableArray *imageCache, and this croaks with a range error.

How can I ask an NSMutableArray whether it has anything for a particular index?

like image 388
Dan Ray Avatar asked Dec 02 '22 05:12

Dan Ray


2 Answers

The NSArray cluster class cannot store nil. So I think it is sufficient to simply check the bounds:

NSUInteger index = xyz; 
if (index < [imageCache count]) { 
    id myObject = [imageCache objectAtIndex:index]; 
}
like image 105
Alex Reynolds Avatar answered Dec 11 '22 15:12

Alex Reynolds


What I find really useful is having a safeObjectAtIndex: method. This will do the check for you and will return nil if the index is out of range.

Just create a new category on NSArray and include the following methods:

- (id)safeObjectAtIndex:(NSUInteger)index;
{
    return ([self arrayContainsIndex:index] ? [self objectAtIndex:index] : nil);
}

- (BOOL)arrayContainsIndex:(NSUInteger)index;
{
    return NSLocationInRange(index, NSMakeRange(0, [self count]));
}
like image 45
diederikh Avatar answered Dec 11 '22 15:12

diederikh