NSDictionary可以調起 setValue:forKey:、setValue:forKeyPath:,無法調起 setObject:forKey:。能調起的也不能真正的進行操作,這取決與不可變字典不可增刪改的特性。
NSMutableDictionary都可以調起
然后看一下setObject:forKey: 、 setValue:forKey: 、 setValue:forKeyPath: 的標准調用語句:
[muDict setValue:<#(nullable id)#> forKeyPath:<#(nonnull NSString *)#>];
[muDict setObject:<#(nonnull id)#> forKey:<#(nonnull id<NSCopying>)#>];
明顯可以看出:
(1) setValue:forKey: 的value是可以為nil的(但是當value為nil的時候,會自動調用removeObject:forKey方法);
setObject:forKey: 的value則不可以為nil。
(2) setValue:forKey: 的key必須是不為nil的字符串類型;
setObject:forKey: 的key可以是不為nil的所有類型。
NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithDictionary:@{ @" cs ": @" test "}];
NSDictionary *testDict = @{ @" name ": @" test_name ", @" age ": @" 12 ", @" dict ":dict};
NSMutableDictionary *muDict = [NSMutableDictionary dictionaryWithDictionary:testDict];
[muDict setObject: @" object " forKey: @" key "];
[muDict setValue: @" value " forKey: @" key2 "];
{
age = 12;
dict = {
cs = test;
};
key = object;
key2 = value;
name = " test_name ";
}
這里setObject:forKey:與setValue:forKey:的作用是相同的,先檢測muDict中是否存在key對應的鍵值對,存在就直接替換原有的value,否者就插入一條新鍵值對。
NSLog( @" %@ ", muDict);
{
age = 12;
dict = {
cs = ceshi;
};
key = object;
key2 = value;
name = " test_name ";
}
這里是對muDict進行操作,處理復合路徑dict.cs,首先檢測muDict中是否存在dict對應的鍵值對,存在就去檢測dict中是否有cs對應的鍵值對,有則替換value,沒有創建鍵值對,如果muDict中檢測不到dict的存在,那么就停止操作。
setValue:forKey: 與 setValue:forKeyPath:
動態設置: setValue:屬性值 forKey:屬性名(用於簡單路徑)、setValue:屬性值 forKeyPath:屬性路徑(用於復合路徑,例如Person有一個Account類型的屬性,那么person.account就是一個復合屬性)
動態讀取: valueForKey:屬性名 、valueForKeyPath:屬性名(用於復合路徑)