調(diào)試的過(guò)程中還是得注意這個(gè),不然字典莫名其妙的少了點(diǎn)keys,定位很麻煩。
給NSDictionary設(shè)置value時(shí)--value為nil時(shí)程序會(huì)不會(huì)crash?
答:分情況
使用字面量,會(huì)crash
使用setObject:ForKey:會(huì)crash,
使用dictionaryWithObjectsAndKeys:不會(huì)crash,
使用setValue:ForKey:不會(huì)crash。
直接賦值dict[@"key"]=nil:不會(huì)crash。
詳細(xì)情況可以看下面注釋
NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithObjectsAndKeys:
@"99", @"key1",
@"02", @"key2",
[self value],@"key3",
@"end",@"end", nil];
// 編譯運(yùn)行都可以通過(guò),但是當(dāng)[self value]為空時(shí),后面所有的key和value都無(wú)法添加上了,但是沒(méi)有添加上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"];
// 編譯運(yùn)行都可以通過(guò),但是沒(méi)有添加上key&value,不影響后面的setValue執(zhí)行
[dict setValue:@"~~~" forKey:@"value2"];
[dict setValue:@"[self value]" forKey:@"value3"];
[dict setValue:@"[self " forKey:@"value4"];
dict[@"value"] = [self value];
// 直接賦值也沒(méi)有問(wèn)題
[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);