In my MTLModel subclass I have this:
@property (assign, nonatomic) NSInteger catId;
And of course this in the implementation:
+ (NSDictionary *)JSONKeyPathsByPropertyKey { return @{ @"catId" : @"cat_id" }; }
But what if my server friends decide to change cat_id to a string in the JSON response? How can I handle this case, and convert it to an int so that I don't get Mantle errors?
3 Answers
Answers 1
if([obj isKindOfClass:NSClassFromString(@"__NSCFNumber")]) { //if it is int or number } else { }
May be above method will help you
Answers 2
use id as datatype
@property (assign, nonatomic) id catId;
Answers 3
We also used Mantle for quite some time, but at the end migrated to handwritten parser/serializers, as the task itself seem to be trivial.
Though, we also have this kind of problems: what if server return something we do not expect (e.g. NSDictionary
instead of NSString
).
To prevent our app from crashing we use this simple tool: Fuzzer.
Basically the tool provides a method that takes a sample and a block. The block evaluates several times, each time bringing slightly mutated version of the sample. You can check behaviour of the models/parsers/serializers using the mutants, to ensure that your code handles unexpected data gracefully.
Here is example taken from project's README:
- (void)test { NSDictionary *sample = @{ @“name” : @“John Doe”, @“age” : @42 }; UserDeserializer *deserializer = [UserDeserializer new]; FZRRunner *runner = [FZRRunner runnerWithBuiltinMutationsForSample:sample]; NSArray *reports = [runner enumerateMutantsUsingBlock:^(NSDictionary *mutant) { [deserializer deserializeUser:mutant]; }]; XCTAssertEqual(reports.count, 0); }
0 comments:
Post a Comment