I am using this method in my every application.
-(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;
}
So whenever I am parsing data, I do check like following
e.g.,
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"
So there are 0 percent chances that you will get nil
or NULL
and application will not crash. This thing will work even if your key is not present in response body.
If you want to use it on multiple screens, make one common handler class and add this as class method and use it. I almost used in all application and my apps never crashed because of such nil
and NULL
issues.