说明:
根据传入参数,快速生成字典;
在系统的基础上进行修改,过滤掉字符串长度为0 的参数;
Demo地址
https://github.com/MyHZ/DictionaryFilteredExample
原文件地址:
https://github.com/MyHZ/DictionaryFiltered
CocoaPods支持:
pod 'DictionaryFiltered'
代码
#import <Foundation/Foundation.h>
#define FilteredDictionaryOfVariableBindings(...) [NSDictionary FilteredDictionaryOfVariableBindings:@"" # __VA_ARGS__, __VA_ARGS__]
@interface NSDictionary (ParaProduct)
+ (NSDictionary *)FilteredDictionaryOfVariableBindings:(NSString *)firstArg, ...;
@end
#import "NSDictionary+ParaProduct.h"
@implementation NSDictionary (ParaProduct)
+ (NSDictionary *)FilteredDictionaryOfVariableBindings:(NSString *)firstArg, ...
{
firstArg = [firstArg stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
NSArray *allPara = [firstArg componentsSeparatedByString:@","];
NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithCapacity:allPara.count];
if (firstArg)
{
__block va_list list;
va_start(list, firstArg);
for (id _Nonnull para in allPara)
{
id arg = va_arg(list, id);
if (arg)
{
if ([arg isKindOfClass:[NSString class]])
{
arg = [(NSString *)arg stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
if ([(NSString *)arg length] != 0)
{
[dic setObject:arg forKey:para];
}
}
else
{
[dic setObject:arg forKey:para];
}
}
}
va_end(list);
}
return dic;
}
@end
使用
NSString *sss1 = @"生于成";
NSString *sss2 = @"";
NSString *sss3 = @"333";
NSString *sss4 = @"";
NSString *sss5 = @"让发";
NSString *sss6 = @(333);
NSString *sss9 = @"";
NSString *sss7 = nil;
NSString *sss8 = @"你好是 ";
NSDictionary *dic = FilteredDictionaryOfVariableBindings(sss1,sss2,sss3,sss4,sss5,sss6,sss7,sss8,nil);
NSLog(@"%@",dic);
结果
{
sss1 = "\U751f\U4e8e\U6210";
sss3 = 333;
sss5 = "\U8ba9\U53d1";
sss6 = 333;
sss8 = "\U4f60\U597d\U662f";
}