سؤال

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.

هل كانت مفيدة؟

المحلول

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.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top