Convert NSString to NSURL in JSON array with mantle

Say the following JSON answer is given to me

{
    "images": [
        "http://domain.com/image1.jpg",
        "http://domain.com/image2.jpg",
        "http://domain.com/image3.jpg"
    ]
}

With Mantle, I want to parse these strings and convert them to NSURL, but store them in NSArray.

So my Objective-C model object will look like

@interface MyModel : MTLModel <MTLJSONSerializing>
// Contains NSURLs, no NSStrings
@property (nonatomic, copy, readonly) NSArray *images;
@end

Is there an elegant way to achieve this? Some NSURL array transformers?

+ (NSValueTransformer*)imagesJSONTransformer
{
    return [NSValueTransformer mtl_JSONArrayTransformerWithModelClass:[NSURL class]];
}

Obviously, NSURL is not the result of MTLModel, so this will not work.

+3
source share
1 answer

Unfortunately, Mantle 1.x does not have an easy way to apply an existing transformer (in this case, a transformer named MTLURLValueTransformerName) to each element of the array.

You can do it as follows:

+ (NSValueTransformer*)imagesJSONTransformer {
    NSValueTransformer *transformer = [NSValueTransformer valueTransformerForName:MTLURLValueTransformerName];
    return [MTLValueTransformer transformerWithBlock: ^NSArray *(NSArray *values) {
        NSMutableArray *transformedValues = [NSMutableArray arrayWithCapacity:values.count];
        for (NSString *value in values) {
            id transformedValue = [transformer transformedValue:value];
            if (transformedValue) {
                [transformedValues addObject:transformedValue];
            }
        }
        return transformedValues;
    }];
}

Mantle 2.0 . Mantle 2.0 .

+2

Source: https://habr.com/ru/post/1540811/


All Articles