Skip to content

Instantly share code, notes, and snippets.

@derekli66
Last active March 22, 2017 06:48
Show Gist options
  • Save derekli66/11254b82ddbdbe471930 to your computer and use it in GitHub Desktop.
Save derekli66/11254b82ddbdbe471930 to your computer and use it in GitHub Desktop.
To catch index out of range in NSArray. Use method swizzle to catch out of range exception and NSLog array contents, array count, and the failed index. NSInteger type is used to catch negative index.
// Inspired by Blended Cocoa
// Reference: http://www.blendedcocoa.com/blog/2012/10/25/objective-c-literals-negative-array-subscripts/
#import <objc/runtime.h>
@implementation NSArray (CatchIndexOutOfRange)
+ (void)load
{
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
method_exchangeImplementations(class_getInstanceMethod(self, @selector(objectAtIndexedSubscript:)),
class_getInstanceMethod(self, @selector(DLC_objectAtIndexedSubscript:)));
});
}
// NSInteger is used to catch negative index
- (id)DLC_objectAtIndexedSubscript:(NSInteger)idx
{
id object = nil;
@try {
object = [self DLC_objectAtIndexedSubscript:idx];
}
@catch (NSException *exception) {
if (idx < 0 || idx >= [self count]) {
NSLog(@"array %p index \" %ld \" out of range,\n current count \" %ld \",\n exception name: %@,\n exception reason: %@,\n exception contents: %@", self, idx, [self count], exception.name, exception.reason, self);
}
[exception raise];
}
return object;
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment