365Cocoa

A snippet of Objective-C code per day, 365 days long.
Written by Pieter Omvlee, developer and owner of Bohemian Coding.

Apr 9

Day 40: isValidIndex:

I hate to check if an index I’m accessing in an array is valid; that is, it’s bigger than zero and smaller than the count. I know its essential but it doesn’t quite produce readable code, so once again, I create a category method that wraps it in easily understandable terms.

@implementation NSArray (NSArray_365Cocoa)
- (BOOL)isValidIndex:(NSUInteger)anIndex;
{
  return anIndex >= 0 && anIndex < [self count];
}
@end

  1. 365cocoa posted this