慎用 dictionaryWithObjectsAndKeys:

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:不完全等同,最大的区别有两点:

  1. setValue:forKey:只接受NSString*类型的key
  2. setValue:forKey:当value为nil时,将调用removeObjectForKey:

推荐阅读更多精彩内容

  • 一、类和对象 1.定义:类是具有相同特征和行为的事物的抽象,对象是类的具体化,类是对象的类型。 2.面向对象的三大...
    陈亮宇阅读 259评论 1 6
  • //将NSData转化为NSString NSString* str = [[NSString alloc]...
    吾是小马哥阅读 2,224评论 0 3
  • //将NSData转化为NSString NSString* str = [[NSString alloc] in...
    脱脱夫斯基阅读 967评论 0 52
  • 字符串的创建: 第一种方式: char a[] = "lanOu"; initWithUTF8String:将C语...
    青花_阅读 222评论 0 0
  • //字符串的创建: //第一种方式: char a[] = "lanOu"; //initWithU...
    肉肉要次肉阅读 426评论 0 2