APP闪退原因之一,请求参数为nil

随着第三方框架AFNetworking的兴起,越来越多的人开始使用AFNetworking来调用接口,发送请求.
而在需要请求体的请求中,一般都是使用字典来作为请求体.
字典的初始化有很多种,本人较为常用的是以下这种:

NSDictionary *params = @{ @"key1":value1 ,@"key2":value2};

但是,value的值一般都是动态传入的,所以有存在nil的可能,结果就是你懂的↓

*** Terminating app due to uncaught exception 'NSInvalidArgumentException',
reason: '*** -[__NSPlaceholderDictionary initWithObjects:forKeys:count:]
: attempt to insert nil object from objects[0]'**

那么就有人会说,你应该在传入前判断value是否为nil,或者使用较为安全的方法,如:

[NSDictionary dictionaryWithObjectsAndKeys:value,@"key", nil];

是的,这些方法都可以解决上面存在的问题,但是我懒,懒得写那么多.
所以就决定是你了,去吧,

亮瞎吧.jpg

一个.m文件搞定问题

#import <Foundation/Foundation.h>
#import <objc/message.h>

@implementation NSDictionary (Swizzle)

+ (void)load {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        [objc_getClass("__NSPlaceholderDictionary") swizzleSelector:@selector(initWithObjects:forKeys:count:) withSwizzledSelector:@selector(safeInitWithObjects:forKeys:count:)];
    });
}

- (instancetype)safeInitWithObjects:(const id _Nonnull __unsafe_unretained *)objects forKeys:(const id _Nonnull __unsafe_unretained *)keys count:(NSUInteger)cnt {
    BOOL containNilObject = NO;
    for (NSUInteger i = 0; i < cnt; i++) {
        if (objects[i] == nil) {
            containNilObject = YES;
            NSLog(@"reason: ***object cannot be nil (key: %@)", keys[i]);
        }
    }
    if (containNilObject) {
        NSUInteger nilCount = 0;
        for (NSUInteger i = 0; i < cnt; ++i) {
            if (objects[i] == nil) {
                nilCount ++;
            }
        }
        NSUInteger length = cnt - nilCount;
        if (length > 0) {
            NSUInteger index = 0;
            id __unsafe_unretained newObjects[length];
            id __unsafe_unretained newKeys[length];
            for (NSUInteger i = 0; i < cnt; ++i) {
                if (objects[i] != nil) {
                    newObjects[index] = objects[i];
                    newKeys[index] = keys[i];
                    index ++ ;
                }
            }
            NSLog(@"fixedDictionary:%@",[self safeInitWithObjects:newObjects forKeys:newKeys count:length]);
            return [self safeInitWithObjects:newObjects forKeys:newKeys count:length];
        } else {
            NSLog(@"fixedDictionary:nil (all objects are nil)");
            return nil;
        }
    }
    return [self safeInitWithObjects:objects forKeys:keys count:cnt];
}

+ (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);
    }
}

@end

当然,我写的这个分类还是有局限性的,限性的,性的,的......
它只对以下这种创建字典的方式有效

NSDictionary *params = @{ @"key1":value1 ,@"key2":value2};

导入文件后:


File.png

看看效果吧:

Result.png
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,009评论 19 139
  • AFHTTPRequestOperationManager 网络传输协议UDP、TCP、Http、Socket、X...
    Carden阅读 4,432评论 0 12
  • *面试心声:其实这些题本人都没怎么背,但是在上海 两周半 面了大约10家 收到差不多3个offer,总结起来就是把...
    Dove_iOS阅读 27,219评论 30 472
  • 发现 关注 消息 iOS 第三方库、插件、知名博客总结 作者大灰狼的小绵羊哥哥关注 2017.06.26 09:4...
    肇东周阅读 12,259评论 4 61
  • 下班后,累趴在床上……他!就像风轻抚过你疲倦的面容,靠在你耳边轻喃睡吧 ~而后悄然地带走你疲惫不堪的心灵 当你生病...
    琦晓阅读 310评论 1 1