Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mantle convert 0 and 1 to BOOL automatically?

Does Mantle already converts int values 0 and 1 in JSON to objective-C BOOL values?

I have a model:

@interface MyModel : MTLModel

@property (nonatomic, readonly) BOOL isValid;

@end

And lets say JSON is:

{ is_valid: 0 } OR { is_valid: 1 }

I want to know if Mantle would automatically convert is_valid into Objective-C BOOL value to do I have to explicity mention the following:

+ (NSValueTransformer)isValidJSONTransfermer {
    return [NSValueTransformer mtl_valueMappingTransformerWithDictionary:@{@(0) : @(NO),
                                                                           @(1) : @(YES)}];
}
like image 525
nefarianblack Avatar asked Jul 10 '14 07:07

nefarianblack


3 Answers

Yes, this is handled for you; you don't need to use the mapping transformer.

Mantle internally calls setValue:forKey: to set the value. The 0 or 1 will be an NSNumber, and setValue:forKey: will use the boolValue on NSNumber to get a value, as your property is declared as a BOOL.

This behaviour of Key-Value Coding is described under Scalar and Structure Support.

like image 161
David Snabel-Caunt Avatar answered Nov 11 '22 04:11

David Snabel-Caunt


If you need to convert a string to boolean use this transformer:

+ (NSValueTransformer *)sectionJSONTransformer {
    return [NSValueTransformer mtl_valueMappingTransformerWithDictionary:@{@"0" : @(NO),
                                                                           @"1" : @(YES)}];
}
like image 28
solven Avatar answered Nov 11 '22 05:11

solven


+ (NSValueTransformer *)awesomeJSONTransformer {
    return [NSValueTransformer valueTransformerForName: MTLBooleanValueTransformerName];
}
like image 1
G.daogeng Avatar answered Nov 11 '22 04:11

G.daogeng