How to check NSDictionary values, nil in iPhone
I have one NSDictionary and that dictionary keys and values ββare dynamically added. Now I want to check if none of the values ββare nil and then set an empty string for that key. How can I check this? Now I check this using conditions, but is there an easy way to check for null or empty values. Please help me, thanks
source to share
NSDictionary
does not contain values nil
for its keys.
If you want to check for the presence / absence of a specific key value, you can use -objectForKey:
. The method returns nil
if there is no key / value pair.
For "nulls", you have to expand what is considered null in the context of your program (for example, some people use NSNull
null to specify null, or if you work with strings as values).
source to share
For any key for which you did not provide a value, your dictionary will return nil
from -objectForKey:
- in other words, if there are no values ββfor the given key, that key does not exist in the dictionary.
However, it looks like you have a list of keys that you would like to have a placeholder value in the dictionary, with that placeholder value being an empty string. For this, you want to do something like this:
- (void)addPlaceholdersForKeys:(NSArray *)keys toDictionary:(NSMutableDictionary *)dictionary {
for (id key in keys) {
if ([dictionary objectForKey:key] == nil) {
[dictionary setObject:@"" forKey:key];
}
}
}
source to share
NSDictionary
and others collections
cannot contain values nil
. But it must store null . You can check it like this: -
if (dictionary[key] == [NSNull null]) {
[dictionary setObject:@"" forKey:key];
}
For a more appropriate code example: -
NSMutableDictionary *dict=[NSMutableDictionary dictionary];
[dict setObject:@"test" forKey:@"key1"];
[dict setObject:@"test1" forKey:@"key2"];
[dict setObject:[NSNull null] forKey:@"key3"];
NSLog(@"%@",dict);
if (dict[@"key3"]==[NSNull null])
{
[dict setObject:@"" forKey:@"key3"];
NSLog(@"%@",dict);
}
Output: -
Before setting empty: -
{
key1 = test;
key2 = test1;
key3 = "<null>";
}
After setting empty: -
{
key1 = test;
key2 = test1;
key3 = "";
}
source to share