慎用 dictionaryWithObjectsAndKeys:
2019-03-19 本文已影响0人
阶梯
NSDictionary* items2=[NSDictionary dictionaryWithObjectsAndKeys:
[d objectForKey:@"GZDBH"],@"工作单编号",
[d objectForKey:@"LDSJ"],@"来电时间",
[d objectForKey:@"SLWCSJ"],@"受理完成时间",
[d objectForKey:@"SLR"],@"受理人",
nil];
但是后来发现items2中始终只有一个对象“工作单编号“,检查后发现,其中“来电时间”对象是空,而dictionaryWithObjectsAndKeys方法在遇到nil对象时,会以为是最终的结束标志。于是items中只放了一个对象就初始化结束了,而且不管编译和运行中都不会报错,这样的bug显然很隐蔽。
NSString* string1 = nil;
NSString* string2 = @"string2";
NSDictionary* dic = [NSDictionary dictionaryWithObjectsAndKeys:
string1, @"string1",
string2, @"string2",
@"string3", @"string3", nil];
string1为nil,不仅会使从dic中取string2时发现string2为nil,并且在取我们认为肯定不为nil的string3时,string3也为nil,这就有可能引发各种意外。
那么解决方案就是当object有可能为nil的时候,采用setObject:forKey:
NSString* string1 = nil;
NSString* string2 = @"string2";
NSMutableDictionary* dic = [NSMutableDictionary dictionary];
if (string1) {
[dic setObject:string1 forKey:@"string1"];
}
if (string2) {
[dic setObject:string2 forKey:@"string2"];
}
[dic setObject:@"string3" forKey:@"string3"];
当然还有更便捷的方法,使用setValue:forKey:
NSString* string1 = nil;
NSString* string2 = @"string2";
NSMutableDictionary* dic = [NSMutableDictionary dictionary];
[dic setValue:string1 forKey:@"string1"];
[dic setValue:string2 forKey:@"string2"];
[dic setValue:@"string3" forKey:@"string3"];
请注意,setValue:forKey:与setObject:forKey:不完全等同,最大的区别有两点:
- setValue:forKey:只接受NSString*类型的key
- setValue:forKey:当value为nil时,将调用removeObjectForKey: