5

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)}];
}
nefarianblack
  • 802
  • 8
  • 16

3 Answers3

6

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.

David Snabel-Caunt
  • 57,804
  • 13
  • 114
  • 132
2

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

+ (NSValueTransformer *)sectionJSONTransformer {
    return [NSValueTransformer mtl_valueMappingTransformerWithDictionary:@{@"0" : @(NO),
                                                                           @"1" : @(YES)}];
}
Stunner
  • 12,025
  • 12
  • 86
  • 145
solven
  • 71
  • 4
1
+ (NSValueTransformer *)awesomeJSONTransformer {
    return [NSValueTransformer valueTransformerForName: MTLBooleanValueTransformerName];
}
DanielBarbarian
  • 5,093
  • 12
  • 35
  • 44
G.daogeng
  • 51
  • 1
  • 5