Last active
March 22, 2017 06:48
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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