iOS NSString 截取字符串常用方法异常捕获

相关问题:CrashDoctor Diagnosis: Application threw exception NSRangeException: *** -[__NSCFString substringToIndex:]: Index 28 out of bounds; string length 26
下面就针对以下方法进行异常捕获 substringToIndex;、substringFromIndexsubstringWithRange。添加NSStringcategory 进行异常处理;核心代码如下:
// 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];
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容