使用RKObjectMapping映射NSDate的NSArray

时间:2013-07-30 17:20:34

标签: objective-c restkit-0.20

假设我有这个Json:

{ "arrayOfDates" : [ "7-28-2013", "7-29-2013", "7-30-2013"]}

我的目标是:

@interface MyObject : NSObject

@property (nonatomic, retain) NSArray* dates;

@end

我尝试使用日期映射arrayOfDates。

RKObjectMapping* mapping = [RKObjectMapping mappingForClass:[MyObject class]];
[mapping addAttributeMappingsFromDictionary:@{@"arrayOfDates" : @"dates"}];
NSDateFormatter *dateFormatter = [NSDateFormatter new];
[dateFormatter setDateFormat:@"MM-dd-yyyy"];
mapping.preferredDateFormatter = dateFormatter;

映射结果是一个NSString数组! 这是获取NSDate数组而不是NSString的方法吗?

2 个答案:

答案 0 :(得分:1)

你无法让RestKit去做。相反,在RestKit调用的完成块中迭代dates并使用格式化程序转换字符串,然后更新dates

如果目标属性是NSDate,RestKit通常会将字符串转换为日期,但在您的情况下,它是一个数组,因此RestKit不知道它应该被转换。

答案 1 :(得分:0)

我遇到了这个试图解决类似问题的答案。我找到了一种让RestKit使用自定义RKValueTransformer执行此操作的方法。

    RKObjectMapping* objectMapping = [RKObjectMapping mappingForClass:[MyObjectWithAnNSArrayProperty class]];

    RKAttributeMapping* datesAttributeMapping = [RKAttributeMapping attributeMappingFromKeyPath:@"arrayOfDates" toKeyPath:NSStringFromSelector(@selector(myArrayOfDates))];
    datesAttributeMapping.valueTransformer = [RKBlockValueTransformer
    valueTransformerWithValidationBlock:^BOOL(__unsafe_unretained Class sourceClass, __unsafe_unretained Class destinationClass)
    {
        // We transform a `NSArray` into another `NSArray`
        return ([sourceClass isSubclassOfClass:[NSArray class]] &&
                [destinationClass isSubclassOfClass:[NSArray class]]);
    }
    transformationBlock:^BOOL(id inputValue, __autoreleasing id *outputValue, Class outputValueClass, NSError *__autoreleasing *error)
    {
        // Validate the input and output
        RKValueTransformerTestInputValueIsKindOfClass(inputValue, [NSArray class], error);
        RKValueTransformerTestOutputValueClassIsSubclassOfClass(outputValueClass, [NSArray class], error);

        NSArray* inputValueArray = inputValue;

        NSMutableArray* result = [[NSMutableArray alloc] initWithCapacity:inputValueArray.count];
        // Convert strings to dates
        for (NSString* inputDate in inputValueArray)
        {
            [result addObject:RKDateFromString(inputDate)];
        }
        // Get a non-mutable copy
        *outputValue = [result copy];
        return YES;
    }];
    [objectMapping addPropertyMapping:datesAttributeMapping];