問題描述
Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[<__NSDictionaryI 0x608000465600> setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key selectedStatus.'
? ? ? ?先說一下我遇到這個問題時的情況:一個 cell 在正常顯示情況下它的右邊不會出現(xiàn)任何的東西(其實這個 cell 在創(chuàng)建的時候右邊是添加了一個 imageView的抖誉,只是創(chuàng)建好之后它默認(rèn)是不顯示的)刊驴,但是當(dāng)它被選中之后右邊的 imageView 就會顯示出來,在數(shù)據(jù)源數(shù)組中存放的是和 cell 一一對應(yīng)的一個不可變字典偎蘸,在字典中有一個 BOOL 類型的值來控制 cell 右邊 imageView 的顯示秩彤。在 cell 被選中之后需要從數(shù)據(jù)源數(shù)組中取出對應(yīng)的不可變字典來改變其中控制 imageView 顯示的 BOOL 值,改完之后重新覆蓋回數(shù)據(jù)源數(shù)組中去,替換當(dāng)前 cell 所對應(yīng)的字典晴楔。然后刷新當(dāng)前 cell 所對應(yīng)的這一行顿苇。
決解辦法
NSDictionary *selectedDic =self.dataSource[indexPath.row];
下面的這一步很關(guān)鍵,假如沒有這一步程序就會 Creash 滥崩,因為在數(shù)組中的不可變字典不會響應(yīng) setObject:forKey: 或者 setValue:forKey:方法
NSMutableDictionary *newDic = selectedDic.mutableCopy;
NSNumber *number = selectedDic[@"selectedStatus"];
BOOL isShow = [number boolValue];
BOOL newStatus = !isShow;
可變字典使用該方法更新字典中的值就不會有問題岖圈,假如這里不使用可變字典 newDic 而是使用不可變字典 selectedDic ,那么就會遇到上面的問題
[newDic setValue:@(newStatus) forKey:@"selectedStatus"];
[self.dataSource replaceObjectAtIndex :indexPath.row withObject :newDic];
[tableView ?reloadRowsAtIndexPaths:@[indexPath]withRowAnimation:UITableViewRowAnimationAutomatic];