简体   繁体   中英

Map NSArray with timestamps to NSDate objects with Mantle in iOS

For example, I have an MTLModel subclass Order with properties

 @property (nonatomic, copy) NSArray *dates;
 @property (nonatomic, strong) NSDate *dateFrom;
 @property (nonatomic, strong) NSDate *dateTo;

JSON that comes from server looks like:

 order =     {
    dates =         (
        1422784800,
        1422784843
    );
}

Is it possible somehow , mb in + (NSValueTransformer *)datesJSONTransformer to convert these two timestamps in JSON to NSDate objects? (dateTo, dateFrom pr-s of class)

Mantle 1.x doesn't provide an easy way to map a field in JSON to multiple model properties. Given the following model implementation below, this should work:

NSDictionary *JSONDictionary = @{
    @"dates" :  @[ @1422784800, @1422784843 ]
};
NSError *error = nil;
Order *order = [MTLJSONAdapter modelOfClass:Order.class fromJSONDictionary:JSONDictionary error:&error];
NSLog(@"Order is from %@ to %@", order.dateFrom, order.dateTo);

Order implementation:

@implementation Order

- (NSDate *)dateFrom
{
    if ([self.dates count] > 0) {
        return self.dates[0];
    }
    return nil;
}

- (NSDate *)dateTo
{
    if ([self.dates count] > 1) {
        return self.dates[1];
    }
    return nil;
}

#pragma mark - MTLJSONSerializing

+ (NSDictionary *)JSONKeyPathsByPropertyKey
{
    return @{
        @"dates" : @"dates"
    };
}

+ (NSValueTransformer *)datesJSONTransformer
{
    return [MTLValueTransformer transformerWithBlock:^NSArray *(NSArray *dates) {
        if (![dates isKindOfClass:NSArray.class]) {
            return nil;
        }
        NSMutableArray *dateObjects = [NSMutableArray arrayWithCapacity:dates.count];
        for (NSNumber *timestamp in dates) {
            NSDate *date = [NSDate dateWithTimeIntervalSince1970:[timestamp doubleValue]];
            [dateObjects addObject:date];
        }
        return [dateObjects copy];
    }];
}

@end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM