隨著第三方框架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