引言
最近有用户总是提出,使用APP过程中,莫名其妙的闪退。查找原因发现,后台的数据有一些更改,有些字段不用了。但之前写的时候还用到了。导致APP闪退了。经理觉得APP不够健壮。让我处理一下,希望,后台不管出现任何情况,APP都不会导致闪退。
在网上找了一些方法。都说使用runtime来解决。然后就在网上找方法。很多都写的是关于数组防闪退的,还不是很全面。
目的
希望以后小伙伴遇到这种问题的时候能快速解决。
直接上代码:
数组添加,插入空值时处理
方法交换
+ (void)swizzleSelector:(SEL)originalSelector withSwizzledSelector:(SEL)swizzledSelector
{
Class class = [self class];
Method originalMethod = class_getInstanceMethod(class, originalSelector);
Method swizzledMethod = class_getInstanceMethod(class, swizzledSelector);
// 若已经存在,则添加会失败
BOOL didAddMethod = class_addMethod(class,originalSelector, method_getImplementation(swizzledMethod), method_getTypeEncoding(swizzledMethod));
// 若原来的方法并不存在,则添加即可
if (didAddMethod) {
class_replaceMethod(class,swizzledSelector, method_getImplementation(originalMethod), method_getTypeEncoding(originalMethod));
} else {
method_exchangeImplementations(originalMethod, swizzledMethod);
}
}
+ (void)load {
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
[self swizzleSelector:@selector(removeObject:)withSwizzledSelector:@selector(safeRemoveObject:)];
[objc_getClass("__NSArrayM") swizzleSelector:@selector(addObject:) withSwizzledSelector:@selector(safeAddObject:)];
[objc_getClass("__NSArrayM") swizzleSelector:@selector(removeObjectAtIndex:) withSwizzledSelector:@selector(safeRemoveObjectAtIndex:)];
[objc_getClass("__NSArrayM") swizzleSelector:@selector(insertObject:atIndex:) withSwizzledSelector:@selector(safeInsertObject:atIndex:)];
[objc_getClass("__NSPlaceholderArray") swizzleSelector:@selector(initWithObjects:count:) withSwizzledSelector:@selector(safeInitWithObjects:count:)];
[objc_getClass("__NSArrayM") swizzleSelector:@selector(objectAtIndex:) withSwizzledSelector:@selector(safeObjectAtIndex:)];
});
代码比较多,就不一一上传了。代码上传至GitHub:https://github.com/wenjing0628/ArraySwizzing 觉得好请给星star.
关于字典和可变字典,数据异常闪退问题
+ (void)load {
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
Class class = NSClassFromString(@"__NSDictionaryM");
[class gl_swizzleMethod:@selector(setObject:forKey:) withMethod:@selector(gl_setObject:forKey:)];
[class gl_swizzleMethod:@selector(setObject:forKeyedSubscript:) withMethod:@selector(gl_setObject:forKeyedSubscript:)];
});
}
- (void)gl_setObject:(id)anObject forKey:(id<NSCopying>)aKey {
if (!aKey) {
NSLog(@"字典key为空 %s",__FUNCTION__);
return;
}
if (!anObject) {
anObject = [NSNull null];
NSLog(@"字典value为空 %s",__FUNCTION__);
}
[self gl_setObject:anObject forKey:aKey];
}
- (void)gl_setObject:(id)obj forKeyedSubscript:(id<NSCopying>)key {
if (!key) {
NSLog(@"字典key为空 %s",__FUNCTION__);
return;
}
if (!obj) {
obj = [NSNull null];
NSLog(@"字典value为空 %s",__FUNCTION__);
}
[self gl_setObject:obj forKeyedSubscript:key];
}
@end
到这里就结束了。好长时间没有写博客。都不知道该怎么写了。写的不好。需要用的,请到GitHub中下载。功能已经验证过,没有问题。category 中的文件直接引用到您的项目中就可以了。上班时间花了几个小时弄的,觉得有用的,请给星。谢谢!!!!!!!