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

前端 未结 15 1561
北海茫月
北海茫月 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:08

    If you are dealing with an "unstable" API, you may want to iterate through all the keys to check for null. I created a category to deal with this:

    @interface NSDictionary (Safe)
    -(NSDictionary *)removeNullValues;
    @end
    
    @implementation NSDictionary (Safe)
    
    -(NSDictionary *)removeNullValues
    {
        NSMutableDictionary *mutDictionary = [self mutableCopy];
        NSMutableArray *keysToDelete = [NSMutableArray array];
        [mutDictionary enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
            if (obj == [NSNull null]) 
            {
                [keysToDelete addObject:key];
            }
        }];
        [mutDictinary removeObjectsForKeys:keysToDelete];
        return [mutDictinary copy];
    }
    @end
    

提交回复
热议问题