NSMutableDictionary setValue与setObject

1,441 阅读1分钟

关于这个问题我们先看一段代码:

NSMutableDictionary *dict = [NSMutableDictionary dictionary];

[dict setValue:nil forKey:@"name"];

此时的value为nil,但是没有产生Crash

@interface NSMutableDictionary<KeyType, ObjectType>(NSKeyValueCoding)

/* Send -setObject:forKey: to the receiver, unless the value is nil, in which case send -removeObjectForKey:.*/

- (void)setValue:(nullable ObjectType)value forKey:(NSString *)key;

@end

从苹果的文档来看,扩展NSMutableDictionary的一个类别,发送setObject:forKey 给接收者,也就是调用setObject:forKey方法

除非value为nil的时候,调用方法removeObjectforKey:    此时不会往字典里面存数据