前言
最近項(xiàng)目中因?yàn)閿?shù)據(jù)問(wèn)題逆趣,導(dǎo)致了KVC由字典轉(zhuǎn)數(shù)據(jù)model時(shí)產(chǎn)生了崩潰嗜历,原因是后臺(tái)返回的數(shù)據(jù)中存在key對(duì)應(yīng)的value為空宣渗,導(dǎo)致了重寫的setNilValueForKey方法拋出異常梨州。
模擬Crash
{
name = null;
age = 24;
}
在OC中模擬的話可以將value設(shè)置為[NSNull null]痕囱;
調(diào)用setValuesForKeysWithDictionary修改Model中對(duì)應(yīng)key的屬性暴匠,將字典類型數(shù)據(jù)轉(zhuǎn)化為model鞍恢。此時(shí)如果model類中未重寫setNilValueForKey方法系統(tǒng)將拋出以下類似錯(cuò)誤:
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '[<People 0x100200080> setNilValueForKey]: could not set nil as the value for the key name.'
所以我們需要再model類中重寫setNilValueForKey方法每窖,為value為空的key設(shè)置默認(rèn)值帮掉,也可以不做處理窒典。
我們定義的model中已經(jīng)重寫了setNilValueForKey方法蟆炊,但多寫了一句話:調(diào)用了父類的這個(gè)方法:[super setNilValueForKey:key]瀑志,同樣引起了Craash??????
- (void)setNilValueForKey:(NSString *)key
{
[super setNilValueForKey:key];
}
刪除[super setNilValueForKey:key]就可以正常運(yùn)行了涩搓,這個(gè)問(wèn)題隱藏了好久劈猪,疏忽了??