调试的过程中还是得注意这个,不然字典莫名其妙的少了点keys,定位很麻烦。
给NSDictionary设置value时--value为nil时程序会不会crash?
答:分情况
-
使用字面量,会crash
-
使用setObject:ForKey:会crash,
-
使用dictionaryWithObjectsAndKeys:不会crash,
-
使用setValue:ForKey:不会crash。
-
直接赋值dict[@"key"]=nil:不会crash。
详细情况可以看下面注释
NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithObjectsAndKeys:
@"99", @"key1",
@"02", @"key2",
[self value],@"key3",
@"end",@"end", nil];
// 编译运行都可以通过,但是当[self value]为空时,后面所有的key和value都无法添加上了,但是没有添加上key&value
NSDictionary *dict2 = @{
@"key1": @"99",
@"key2": @"02",
@"key3":[self value],
@"end":@"end"};
//*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[__NSPlaceholderDictionary initWithObjects:forKeys:count:]: attempt to insert nil object from objects[2]'
[dict setValue:[self value] forKey:@"value"];
// 编译运行都可以通过,但是没有添加上key&value,不影响后面的setValue执行
[dict setValue:@"~~~" forKey:@"value2"];
[dict setValue:@"[self value]" forKey:@"value3"];
[dict setValue:@"[self " forKey:@"value4"];
dict[@"value"] = [self value];
// 直接赋值也没有问题
[dict setObject:[self value] forKey:@"value"];
// *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[__NSDictionaryM setObject:forKey:]: object cannot be nil (key: value)'
NSLog(@"%@", dict);
网友评论