我在我的每一个应用程序中使用这种方法,你可以随便写。
-(NSString*)checkNullValidation:(NSString *)key {
NSString *returnValue;
if(key == (id)[NSNull null] || [key isEqual:[NSNull null]] || key == nil) {
returnValue = @"";
}
else {
returnValue = [NSString stringWithFormat:@"%@",key];
}
return returnValue;
}
所以每当我解析数据,我做检查像下面 例如,
NSDictionary *dictionaryTest = @{@"MyFirstKey":nil, @"MySecondKey":@"AwesomeValue"};
NSString *firstValue = [self checkNullValidation:[dictionaryTest valueForKey:@"MyFirstKey"]]; // It will be @"" instead of nil
NSString *secondValue = [self checkNullValidation:[dictionaryTest valueForKey:@"MySecondKey"]]; // It will be @"AwesomeValue"
因此,有百分之0的机会,你会得到nil
或NULL
和应用程序不会崩溃。即使你的钥匙没有出现在响应主体中,这个东西也能工作。
如果您想在多个屏幕上使用它,请制作一个通用处理程序类并将其添加为类方法并使用它。我几乎用于所有应用程序,我的应用程序从未崩溃,因为这样的nil
和NULL
问题。
该是否有多种可能的解决方案来处理所有的'nil'和'NSNull'(是的,你必须同时处理)。例如,您可以尝试http://stackoverflow.com/a/23610588/669586。或者创建一个宏。 – Sulthan