Checking a null value in Objective-C that has been returned from a JSON string

前端 未结 15 1529
北海茫月
北海茫月 2020-11-30 20:34

I have a JSON object that is coming from a webserver.

The log is something like this:

{          
   \"status\":\"success\",
   \"Us         


        
15条回答
  •  春和景丽
    2020-11-30 21:27

    if you have many attributes in json, using if statement to check them one by one is troublesome. What even worse is that the code would be ugly and hard to maintain.

    I think the better approach is creating a category of NSDictionary:

    // NSDictionary+AwesomeDictionary.h
    
    #import 
    
    @interface NSDictionary (AwesomeDictionary)
    - (id)validatedValueForKey:(NSString *)key;
    @end
    
    // NSDictionary+AwesomeDictionary.m
    
    #import "NSDictionary+AwesomeDictionary.h"
    
    @implementation NSDictionary (AwesomeDictionary)
    - (id)validatedValueForKey:(NSString *)key {
        id value = [self valueForKey:key];
        if (value == [NSNull null]) {
            value = nil;
        }
        return value;
    }
    @end
    

    after importing this category, you can:

    [json validatedValueForKey:key];
    

提交回复
热议问题