Mantle convert 0 and 1 to BOOL automatically?

你离开我真会死。 提交于 2019-12-10 15:45:03

问题


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)}];
}

回答1:


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.




回答2:


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

+ (NSValueTransformer *)sectionJSONTransformer {
    return [NSValueTransformer mtl_valueMappingTransformerWithDictionary:@{@"0" : @(NO),
                                                                           @"1" : @(YES)}];
}



回答3:


+ (NSValueTransformer *)awesomeJSONTransformer {
    return [NSValueTransformer valueTransformerForName: MTLBooleanValueTransformerName];
}


来源:https://stackoverflow.com/questions/24670702/mantle-convert-0-and-1-to-bool-automatically

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!