1. 程式人生 > >iOS-could not set nil as the value for the key

iOS-could not set nil as the value for the key

從後臺請求到的資料往往存在空值, 這時前臺便無法處理資料, 賦值model屬性的時候出現: could not set nil as the value for the key的報錯.這時可用下列方式解決:

1. 在model的基類中重寫setnilvalueforkey:

- (void)setNilValueForKey:(NSString *)key{
    [self setValue:@"" forKey:key];
}

2. 另外網上給出了另一個解決方案, 你如果使用網路請求類是AFN那麼可以通過設定AFN中responseSerializer的removesKeysWithNullValues屬性來規避空值

/**
 Whether to remove keys with `NSNull` values from response JSON. Defaults to `NO`.
 */
@property (nonatomic, assign) BOOL removesKeysWithNullValues;
((AFJSONResponseSerializer *)session.responseSerializer).removesKeysWithNullValues