常见错误:
NSInvalidArgumentException
-[NSNull containsString:]: unrecognized selector sent to instance 0x1f4db9c00xxxx + 229708
[__NSArrayM objectAtIndexedSubscript:]: index 1 beyond bounds for empty arrayxxx + 554240
(防止数据为空引起崩溃)
第一步:
https://github.com/nicklockwood/NullSafe
下载这个Demo,只要将其中的NullSafe.m文件移到依赖的工具包里面即可,不需要引用,它有运行时自引用(#import <objc/runtime.h>会运行时自引用)。
第二步:
可以通过下面代码测出:[NSNull containsString:]这个bug。
代码如下:
NSMutableDictionary *tempDict = [NSMutableDictionary new];
[tempDict setObject:[NSNull null] forKey:@"strv"];
if([tempDict[@"strv"] containsString:@"A"]){
}
(防止数据越界引起崩溃)
第三步:
增加这个NSArray+BeyondIntercept.m文件,不需要引用,它有运行时自引用(#import <objc/runtime.h>会运行时自引用)。
第四步:NSArray+BeyondIntercept.m文件的具体代码
#import <objc/runtime.h>
#import <Foundation/Foundation.h>
// 防止数据越界
@implementation NSArray (BeyondIntercept)
+ (void)load {
Method oldObjectAtIndex = class_getInstanceMethod(objc_getClass("__NSArrayI"), @selector(objectAtIndex:));
Method newObjectAtIndex = class_getInstanceMethod(objc_getClass("__NSArrayI"), @selector(newObjectAtIndex:));
method_exchangeImplementations(oldObjectAtIndex, newObjectAtIndex);
Method oldMutableObjectAtIndex = class_getInstanceMethod(objc_getClass("__NSArrayI"), @selector(objectAtIndexedSubscript:));
Method newMutableObjectAtIndex = class_getInstanceMethod(objc_getClass("__NSArrayI"), @selector(newObjectAtIndexedSubscript:));
method_exchangeImplementations(oldMutableObjectAtIndex, newMutableObjectAtIndex);
Method oldMObjectAtIndex = class_getInstanceMethod(objc_getClass("__NSArrayM"), @selector(objectAtIndex:));
Method newMObjectAtIndex = class_getInstanceMethod(objc_getClass("__NSArrayM"), @selector(newMutableObjectAtIndex:));
method_exchangeImplementations(oldMObjectAtIndex, newMObjectAtIndex);
Method oldMMutableObjectAtIndex = class_getInstanceMethod(objc_getClass("__NSArrayM"), @selector(objectAtIndexedSubscript:));
Method newMMutableObjectAtIndex = class_getInstanceMethod(objc_getClass("__NSArrayM"), @selector(newMutableObjectAtIndexedSubscript:));
method_exchangeImplementations(oldMMutableObjectAtIndex, newMMutableObjectAtIndex);
}
- (id)newObjectAtIndex:(NSUInteger)index {
@try {
return [self newObjectAtIndex:index];
} @catch (NSException * exception) {
NSLog(@"Fatal: %@ %@", exception.name, exception.reason);
return nil;
}
}
- (id)newObjectAtIndexedSubscript:(NSUInteger)index {
@try {
return [self newObjectAtIndexedSubscript:index];
} @catch (NSException *exception) {
NSLog(@"Fatal: %@ %@", exception.name, exception.reason);
return nil;
}
}
- (id)newMutableObjectAtIndex:(NSUInteger)index {
@try {
return [self newMutableObjectAtIndex:index];
} @catch (NSException *exception) {
NSLog(@"Fatal: %@ %@", exception.name, exception.reason);
return nil;
}
}
- (id)newMutableObjectAtIndexedSubscript:(NSUInteger)index {
@try {
return [self newMutableObjectAtIndexedSubscript:index];
} @catch (NSException *exception) {
NSLog(@"Fatal: %@ %@", exception.name, exception.reason);
return nil;
}
}
@end
更多开发问题,可加V。感谢同事帮我解决了问题。