iosobjective-cgithub-mantle

Validating each property before returning object


While using Mantle, is there a possibility to before returning the object we are creating (on this case via JSON) to verify that X and Y properties are not nil?

Imagine this class:

@interface Person : MTLModel <MTLJSONSerializing>

@property(nonatomic,strong,readonly)NSString *name;
@property(nonatomic,strong,readonly)NSString *age;

@end

I want a way to verify that if the JSON I received doesn't have the name (for some reason there was an issue on server's DB) I will return a nil Person, as it doesn't make sense to create that object without that property set.


Solution

  • You can use the MTLJSONSerializing protocol method classForParsingJSONDictionary: to return nil rather than an invalid object:

    // In your MTLModelSubclass.m
    //
    + (Class)classForParsingJSONDictionary:(NSDictionary *)JSONDictionary {
        if (JSONDictionary[@"name"] == nil || JSONDictionary[@"age"] == nil) {
            return nil;
        }
        return self.class;
    }