Search code examples
iosobjective-cgithub-mantle

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 , m.b. in + (NSValueTransformer *)datesJSONTransformer to convert these two timestamps in JSON to NSDate objects? (dateTo, dateFrom pr-s of class)


Solution

  • 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