APP閃退原因之一,請求參數(shù)為nil

隨著第三方框架AFNetworking的興起,越來越多的人開始使用AFNetworking來調(diào)用接口,發(fā)送請求.
而在需要請求體的請求中,一般都是使用字典來作為請求體.
字典的初始化有很多種,本人較為常用的是以下這種:

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

但是,value的值一般都是動態(tài)傳入的,所以有存在nil的可能,結(jié)果就是你懂的↓

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

那么就有人會說,你應(yīng)該在傳入前判斷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

當(dāng)然,我寫的這個分類還是有局限性的,限性的,性的,的......
它只對以下這種創(chuàng)建字典的方式有效

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

導(dǎo)入文件后:


File.png

看看效果吧:

Result.png
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • Spring Cloud為開發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見模式的工具(例如配置管理,服務(wù)發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 136,695評論 19 139
  • AFHTTPRequestOperationManager 網(wǎng)絡(luò)傳輸協(xié)議UDP、TCP、Http、Socket、X...
    Carden閱讀 5,339評論 0 12
  • *面試心聲:其實這些題本人都沒怎么背,但是在上海 兩周半 面了大約10家 收到差不多3個offer,總結(jié)起來就是把...
    Dove_iOS閱讀 27,656評論 30 472
  • 發(fā)現(xiàn) 關(guān)注 消息 iOS 第三方庫、插件、知名博客總結(jié) 作者大灰狼的小綿羊哥哥關(guān)注 2017.06.26 09:4...
    肇東周閱讀 15,654評論 4 61
  • 下班后,累趴在床上……他!就像風(fēng)輕撫過你疲倦的面容,靠在你耳邊輕喃睡吧 ~而后悄然地帶走你疲憊不堪的心靈 當(dāng)你生病...
    琦曉閱讀 356評論 1 1

友情鏈接更多精彩內(nèi)容