NSMutableDictionary 繼承自 NSDictionary,但多了修改能力。setObject:forKey: 要求 value 與 key 都不能為 nil;若傳入 nil,通常會直接觸發 crash。setValue:forKey: 則是 KVC 風格的寫法,遇到 nil 時通常會移除該 key,因此較不容易因 nil 而崩潰。
NSMutableDictionary *dic = [NSMutableDictionary dictionary]; [dic setObject:@"1" forKey:@"1"]; [dic setObject:@"2" forKey:@"2"]; [dic setValue:@"6" forKey:@"6"]; [dic setValue:nil forKey:@"5"];
如果 value 可能為 nil,建議先判斷,再決定要不要寫入。若希望「有值才寫入、沒值就移除」,可用 setValue:forKey:。但也要注意 key 仍不可為 nil,且若 value 型別不是物件,也要先轉成物件包裝。
setValue:forKey: 不是萬用丹,它只是把 nil 的處理交給 KVC 機制。若 dictionary 宣告為不可變,任何修改都會失敗;若 value 是基本型別,也必須先轉成 NSNumber 或 NSString。