模仿系统的快速生成字典的方法NSDictionaryOfVariableBindings,并过滤掉值为nil
的对象或内容全为空格字符串,防止字典crash。
推荐适用场合:网络请求生成参数字典,无需判空。
其他创建字典的地方也可以使用,注意此方法会过滤掉全为空格及@""
字符串,如不需要可自行修改。
创建分类文件NSDictionary+Safe
NSDictionary+Safe.m 中代码如下:
#define BZDictionaryOfVariableBindings(...) [NSDictionary _BZDictionaryOfVariableBindings:@"" # __VA_ARGS__, __VA_ARGS__]
@interface NSDictionary (Safe)
/**
安全获取value值
@param aKey <#aKey description#>
@return <#return value description#>
*/
- (id)objectForKeyCheck:(id)aKey;
/**
模仿系统的对象生成字典的宏定义:NSDictionaryOfVariableBindings(...)
if v1 = @"something"; v2 = nil; v3 = @"something"; v4 = @"";
ZXDictionaryOfVariableBindings(v1, v2, v3) is equivalent to [NSDictionary dictionaryWithObjectsAndKeys:v1, @"v1", v3, @"v3", nil];
并且参数的值可为nil,@"", 会自动去除值为nil, @"", @" "等的对象
*/
+ (NSDictionary *)_BZDictionaryOfVariableBindings:(NSString *)firstArg, ...;
NSDictionary+Safe.h 中代码如下:
#import "NSDictionary+Safe.h"
@implementation NSDictionary (Safe)
- (id)objectForKeyCheck:(id)aKey{
if ([self.allKeys containsObject:aKey]) {
return [self objectForKey:aKey];
}
NSLog(@"%@", [NSThread callStackSymbols]);
return nil;
}
+ (NSDictionary *)_BZDictionaryOfVariableBindings:(NSString *)firstArg, ... {
firstArg = [firstArg stringByReplacingOccurrencesOfString:@" " withString:@""];
NSArray *keys = [firstArg componentsSeparatedByString:@","];
NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithCapacity:keys.count];
va_list list;
if (firstArg) {
va_start(list, firstArg);
id arg;
for (NSString *key in keys) {
arg = va_arg(list, id);
if (!arg || [arg isKindOfClass:[NSNull class]]) {
continue;
}
if ([arg isKindOfClass:[NSString class]]) {
if ([[arg stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] length] != 0) {
[dic setObject:arg forKey:key];
}
} else {
[dic setObject:arg forKey:key];
}
}
va_end(list);
}
return dic;
}
拿到后台返回字段,普通的字典添加元素,会crash掉
调用后会发现把nil值过滤掉了不会crash