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
, 开发者_如何学JAVAand this croaks with a range error.
How can I ask an NSMutableArray whether it has anything for a particular index?
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];
}
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]));
}
if (index < [imageCache count])
...
This code answers your question. Unlike the accepted answer, this code handles passing in a negative index value.
if (!NSLocationInRange(index, NSMakeRange(0, [imageCache count]))) {
// Index does not exist
} else {
// Index exists
}
[imageCache count] will return the number of items in your array. Take it from there :-)
Check the number of items in the array first with [imageCache count]. Don't try to ask for anything with an index greater than that result.
精彩评论