IOS 字典赋值方式的区别

setObject:forKey:

@interface NSMutableDictionary : NSDictionary

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

@end

- setObject: forKey 的第一个参数 anObject使用 ObjectType 修饰,其本质(nonnull ObjectType) 默认类型是 nonnull 表示不能为空,如果是空便会崩溃。

anObjectaKey的值,dictionary强引用该对象。如果anObjectnil,会引发NSInvalidArgumentException的异常,如果你想传一个空值在dictionary中,可以使用NSNull代表空值。

setValue:forKey:

@interface NSMutableDictionary(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

- setValue: forKey 的第一个参数value使用nullable ObjectType修饰,表示可以为空。如果是空的话,便会执行-removeObjectForKey

setObject:forKeyedSubscript:

- (void)setObject:(ObjectType)obj forKeyedSubscript:(id)key;

objectaKey的值,dictionary强引用该对象。如果objectnildictionary会将aKey的关联的object移除。objectnildictionary会将aKey的关联的object移除。

NSMutableDictionary *dictM = [[NSMutableDictionary alloc] init];
dictM[@"name"] = @"Tom"; //@{@"name":@"Tom"}
dictM[@"name"] = nil;     //@{}

dictM[@"name"] = @"Tom"字面量赋值 和 [mutableDictionary setObject:@"Tom" forKeyedSubscript:@"name"]是等效的;

特别提醒: 这里的“空”是指 NULL、 Nil、 nil,而[NSNull null] 是指空的对象,其是非空的。

你可能感兴趣的:(IOS 字典赋值方式的区别)