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,这样更加安全;

你可能感兴趣的:(NSMutableDictionary两个set方法的区别)