Chirag Hirpara Chirag Hirpara - 1 year ago 110
iOS Question

How to remove a string containing "<null>" from an NSDictionary

I have dictionary of user information, that is getting filled from web service. There are some fields that content is private so it contains NULL. How do I convert value to an empty string wherever there is the value null as in dictionary below:

"about_me" = "<null>";
"contact_number" = 123456798798;
"display_name" = "err";
followers = 0;
following = 4;
gender = "-";
posts = 0;
"user_id" = 18;
username = charge;
website = "<null>";

Answer Source

The simplest way to do this is to loop through a mutable copy of the dictionary and if the value is
null set the value to the value you want.

NSMutableDictionary *mutableDict = [dict mutableCopy];
for (NSString *key in [dict allKeys]) {
    if ([dict[key] isEqual:[NSNull null]]) {
        mutableDict[key] = @"";//or [NSNull null] or whatever value you want to change it to
dict = [mutableDict copy];

If the value in the dictionary is actually "<null>", replace the conditional with [dict[key] isEqualToString:@"<null>"]

(assuming you're using ARC, otherwise you need to release the copy'd dictionaries)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download