随着第三方框架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];
是的,这些方法都可以解决上面存在的问题,但是我懒,懒得写那么多.
所以就决定是你了,去吧,
一个.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};
导入文件后:
看看效果吧: