NSNull handling for NSManagedObject properties values

后端 未结 5 611
说谎
说谎 2021-01-30 09:07

I\'m setting values for properties of my NSManagedObject, these values are coming from a NSDictionary properly serialized from a JSON file. My problem

5条回答
  •  离开以前
    2021-01-30 09:39

    I wrote a couple of category methods to strip nulls from a JSON-generated dictionary or array prior to use:

    @implementation NSMutableArray (StripNulls)
    
    - (void)stripNullValues
    {
        for (int i = [self count] - 1; i >= 0; i--)
        {
            id value = [self objectAtIndex:i];
            if (value == [NSNull null])
            {
                [self removeObjectAtIndex:i];
            }
            else if ([value isKindOfClass:[NSArray class]] ||
                     [value isKindOfClass:[NSDictionary class]])
            {
                if (![value respondsToSelector:@selector(setObject:forKey:)] &&
                    ![value respondsToSelector:@selector(addObject:)])
                {
                    value = [value mutableCopy];
                    [self replaceObjectAtIndex:i withObject:value];
                }
                [value stripNullValues];
            }
        }
    }
    
    @end
    
    
    @implementation NSMutableDictionary (StripNulls)
    
    - (void)stripNullValues
    {
        for (NSString *key in [self allKeys])
        {
            id value = [self objectForKey:key];
            if (value == [NSNull null])
            {
                [self removeObjectForKey:key];
            }
            else if ([value isKindOfClass:[NSArray class]] ||
                     [value isKindOfClass:[NSDictionary class]])
            {
                if (![value respondsToSelector:@selector(setObject:forKey:)] &&
                    ![value respondsToSelector:@selector(addObject:)])
                {
                    value = [value mutableCopy];
                    [self setObject:value forKey:key];
                }
                [value stripNullValues];
            }
        }
    }
    
    @end
    

    It would be nice if the standard JSON parsing libs had this behaviour by default - it's almost always preferable to omit null objects than to include them as NSNulls.

提交回复
热议问题