Transform NSString to NSURL within a JSON Array with Mantle

a 夏天 提交于 2019-12-07 12:06:58

问题


Let's say given to me is the following JSON response

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

With Mantle I want to parse those strings and transform them into NSURLs but keep them in an NSArray.

So my Objective-C model object would look like

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

Is there an elegant way to achieve that? Some NSURL array transformer?

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

Obviously NSURL does not derive from MTLModel, so that will not work.


回答1:


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

You can do it like this:

+ (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;
    }];
}

In Mantle 2.0, you'll be able to use the predefined array mapping transformer. Mantle 2.0 is still in development.



来源:https://stackoverflow.com/questions/23268124/transform-nsstring-to-nsurl-within-a-json-array-with-mantle

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