Testing NSArray Content Without Risk of Range Error

I say stupidly:

if ([imageCache objectAtIndex:index]) { 

The problem is that for the first time through this, I have NEVER put in my NSMutableArray *imageCache , and this screams with a range error.

How can I query NSMutableArray if it has anything for a specific index?

+4
source share
6 answers

The NSArray cluster NSArray cannot store nil . Therefore, I believe that it is enough to simply check the boundaries:

 NSUInteger index = xyz; if (index < [imageCache count]) { id myObject = [imageCache objectAtIndex:index]; } 
+9
source

What really safeObjectAtIndex: me is the safeObjectAtIndex: method. This will check you and return nil if the index is out of range.

Just create a new category in 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])); } 
+7
source
 if (index < [imageCache count]) ... 
+1
source

This code answers your question. Unlike the accepted answer, this code handles the transmission of a negative index value.

 if (!NSLocationInRange(index, NSMakeRange(0, [imageCache count]))) { // Index does not exist } else { // Index exists } 
+1
source

[imageCache count] will return the number of elements in your array. Take it from there :-)

0
source

First check the number of elements in the array using [imageCache count]. Do not try to ask for anything with an index greater than the specified result.

0
source

Source: https://habr.com/ru/post/1310769/


All Articles