0

假设我有这个 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 的方法吗?

4

2 回答 2

1

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

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

于 2013-07-30T17:26:17.430 回答
0

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

    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];
于 2015-08-28T21:34:54.740 回答