在 iOS 中将带有时间戳的 NSArray 映射到带有 Mantle 的 NSDate 对象

Map NSArray with timestamps to NSDate objects with Mantle in iOS

例如,我有一个 MTLModel subclass Order with properties

 @property (nonatomic, copy) NSArray *dates;
 @property (nonatomic, strong) NSDate *dateFrom;
 @property (nonatomic, strong) NSDate *dateTo;
来自服务器的

JSON 看起来像:

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

是否有可能,m.b。在 + (NSValueTransformer *)datesJSONTransformer 中将 JSON 中的这两个时间戳转换为 NSDate 对象? (dateTo, dateFrom pr-s of class)

Mantle 1.x 没有提供将 JSON 中的字段映射到多个模型属性的简单方法。鉴于下面的模型实现,这应该有效:

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

订单执行:

@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