相关问题:CrashDoctor Diagnosis: Application threw exception NSRangeException: *** -[__NSCFString substringToIndex:]: Index 28 out of bounds; string length 26
下面就针对以下方法进行异常捕获 substringToIndex
;、substringFromIndex
、substringWithRange
。添加NSString
的category
进行异常处理;核心代码如下:
// Swizzling核心代码
+ (void)load {
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
Method fromMethod = class_getInstanceMethod(objc_getClass("__NSCFString"), @selector(substringToIndex:));
Method toMethod = class_getInstanceMethod(objc_getClass("__NSCFString"), @selector(xd_substringToIndex:));
method_exchangeImplementations(fromMethod, toMethod);
Method fromMethod2 = class_getInstanceMethod(objc_getClass("__NSCFString"), @selector(substringFromIndex:));
Method toMethod2 = class_getInstanceMethod(objc_getClass("__NSCFString"), @selector(xd_substringFromIndex:));
method_exchangeImplementations(fromMethod2, toMethod2);
Method fromMethod3 = class_getInstanceMethod(objc_getClass("__NSCFString"), @selector(substringWithRange:));
Method toMethod3 = class_getInstanceMethod(objc_getClass("__NSCFString"), @selector(xd_substringWithRange:));
method_exchangeImplementations(fromMethod3, toMethod3);
});
}
- (id)xd_substringToIndex:(NSUInteger)index {
if (self.length-1 < index) {
@try {
return [self xd_substringToIndex:index];
}
@catch (NSException *exception) {
NSLog(@"---------- %s Crash Because Method %s ----------\n", class_getName(self.class), __func__);
NSLog(@"%@", [exception callStackSymbols]);
return @"";
}
@finally {}
}
else {
return [self xd_substringToIndex:index];
}
}
- (id)xd_substringFromIndex:(NSUInteger)index {
if (self.length-1 < index) {
@try {
return [self xd_substringFromIndex:index];
}
@catch (NSException *exception) {
NSLog(@"---------- %s Crash Because Method %s ----------\n", class_getName(self.class), __func__);
NSLog(@"%@", [exception callStackSymbols]);
return @"";
}
@finally {}
}
else {
return [self xd_substringFromIndex:index];
}
}
- (id)xd_substringWithRange:(NSRange)range {
if (((range.location + range.length) > self.length) || range.location < 0) {
@try {
return [self xd_substringWithRange:range];
}
@catch (NSException *exception) {
NSLog(@"---------- %s Crash Because Method %s ----------\n", class_getName(self.class), __func__);
NSLog(@"%@", [exception callStackSymbols]);
return @"";
}
@finally {}
}
else {
return [self xd_substringWithRange:range];
}
}