Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 776
Rui Peres Avatar asked Apr 25 '14 11:04

Rui Peres


2 Answers

Whilst you could override the initialiser. It seems more concise to override the validate: as this is called at the last stage before Mantle returns the deserialised object. Makes sense to put all your validation logic in a validate method...

See the final line of the MTLJSONAdapter

id model = [self.modelClass modelWithDictionary:dictionaryValue error:error];
return [model validate:error] ? model : nil;

This tells us that if our custom model returns NO from validate, then Mantle will discard the object.

So you could in your subclass simply perform the following:

- (BOOL)validate:(NSError **)error {
    return [super validate:error] && self.name.length > 0; 
}

Ideally in your own implementation you probably want to return an appropriate error.

The validate method will then call Foundation's validateValue:forKey:error: for every property that you registered with Mantle in JSONKeyPathsByPropertyKey. So if you want a more controlled validation setup you could also validate your data here..

like image 57
Daniel Galasko Avatar answered Oct 29 '22 12:10

Daniel Galasko


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;
}
like image 45
David Snabel-Caunt Avatar answered Oct 29 '22 12:10

David Snabel-Caunt