NSMutableDictionary两个set方法的区别

NSMutableDictionary有两个set方法:

方法一:

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

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

这里的value如果是nil,就相当于移除对应的键值;

- (void)setObject:(ObjectType)anObject forKey:(KeyType)aKey;

anObject

The value for aKey. A strong reference to the object is maintained by the dictionary.

key对应的值,字典会对他进行一次强引用

Important

Raises an NSInvalidArgumentException if anObject is nil. If you need to represent a nil value in the dictionary, use NSNull.

如果anObject为nil,会触发异常。如果你需要代表空,可以用NSNull对象来代替;

aKey

The key for value. The key is copied (using copyWithZone:; keys must conform to the NSCopying protocol). If aKey already exists in the dictionary, anObject takes its place.

value对应的值,如果有旧值,就会把旧值给替换掉;

二者的联系是:

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

相当于:

- (void)setObject:(ObjectType)anObject forKey:(KeyType)aKey;

添加nil的时候做了一层保护;因此,我们在使用的时候最好优先使用setValue,这样更加安全;

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容