-
不可变字典NSDictionary
id obj = nil;
//dictionaryWithObjectsAndKeys,value可为nil,运行正常
NSDictionary *dict1 = [NSDictionary dictionaryWithObjectsAndKeys:@"value0",@"key0",obj,@"key1", nil];
//不可变字典NSDictionary,value为nil,crash!
NSDictionary *dict2 = [[NSDictionary alloc] init];
[dict2 setValue:obj forKey:@"key2"];
//冒号键值对写法,value为nil,crash!
NSDictionary *dict3 = @{@"key3":obj};
-
可变字典NSMutableDictionary
id obj = nil;
//可变字段NSMutableDictionary,语法糖写法,value可为nil,运行正常
NSMutableDictionary *dict4 = [[NSMutableDictionary alloc] init];
dict4[@"key4"] = obj;
//setValue,value可为nil,运行正常
//可变字典NSMutableDictionary,调用setValue实际是调用-setObject:forKey,但是当value为nil时,会调用removeObjectForKey,因为value可以为nil
NSMutableDictionary *dict5 = [[NSMutableDictionary alloc] init];
[dict5 setValue:obj forKey:@"key5"];
//setObject,value为nil,crash
NSMutableDictionary *dict6 = [[NSMutableDictionary alloc] init];
[dict6 setObject:obj forKey:@"key6"];
总结:
1. NSDictionary,推荐使用dictionaryWithObjectsAndKeys;
2. NSMutableDictionary,推荐使用语法糖写法或setValue;
3. setObject: forKey:是NSMutableDictionary的特有方法;
4. setObject: forKey,value不可为nil;key为Id类型;
5. setValue: forKey,value可为nil,key必须为NSString;
网友评论