3

以下代码从我的服务器接收 JSON 响应,该响应由一组元素组成,每个元素都有一个“created_at”和一个“updated_at”键。对于所有这些元素,我想删除为这两个键设置的字符串中的单个字符(冒号)。

- (void)objectLoader:(RKObjectLoader*)loader willMapData:(inout id *)mappableData {
    // Convert the ISO 8601 date's colon in the time-zone offset to be easily parsable
    // by Objective-C's NSDateFormatter (which works according to RFC 822).
    // Simply remove the colon (:) that divides the hours from the minutes:
    // 2011-07-13T04:58:56-07:00 --> 2011-07-13T04:58:56-0700 (delete the 22nd char)
    NSArray *dateKeys = [NSArray arrayWithObjects:@"created_at", @"updated_at", nil];
    for(NSMutableDictionary *dict in [NSArray arrayWithArray:(NSArray*)*mappableData])
    for(NSString *dateKey in dateKeys) {
        NSString *ISO8601Value = (NSString*)[dict valueForKey:dateKey];
        NSMutableString *RFC822Value = [[NSMutableString alloc] initWithString:ISO8601Value];
        [RFC822Value deleteCharactersInRange:NSMakeRange(22, 1)];
        [dict setValue:RFC822Value forKey:dateKey];
        [RFC822Value release];
    }
}

但是,该行[dict setValue:RFC822Value forKey:dateKey];引发了一个NSUnknownKeyException带有 message 的问题this class is not key value coding-compliant for the key created_at

我在这里做错了什么?我的主要问题可能是我对这个 inout 声明不太满意......

4

1 回答 1

7

你的 inout 声明对我来说看起来不错。我建议您使用 NSLog 打印 mappableData 以查看它的实际外观。

编辑:根据评论中的讨论,mappableData在这种情况下实际上是JKDictionary对象的集合。JKDictionaryJSONKit.h(RestKit 正在使用的 JSON 解析库)中定义为NSDictionary. 因此,它不是可变字典,也没有实现[NSMutableDictionary setValue:forKey:]. 这就是您在运行时收到 NSUnknownKeyException 的原因。

实现您想要的一种方法可能是这样的(未经测试!):

- (void)objectLoader:(RKObjectLoader*)loader willMapData:(inout id *)mappableData {
    // Convert the ISO 8601 date's colon in the time-zone offset to be easily parsable
    // by Objective-C's NSDateFormatter (which works according to RFC 822).
    // Simply remove the colon (:) that divides the hours from the minutes:
    // 2011-07-13T04:58:56-07:00 --> 2011-07-13T04:58:56-0700 (delete the 22nd char)
    NSArray *dateKeys = [NSArray arrayWithObjects:@"created_at", @"updated_at", nil];
    NSMutableArray *reformattedData = [NSMutableArray arrayWithCapacity:[*mappableData count]];

    for(id dict in [NSArray arrayWithArray:(NSArray*)*mappableData]) {
        NSMutableDictionary* newDict = [dict mutableCopy];
        for(NSString *dateKey in dateKeys) {
            NSMutableString *RFC822Value = [[newDict valueForKey:dateKey] mutableCopy];
            [RFC822Value deleteCharactersInRange:NSMakeRange(22, 1)];
            [newDict setValue:RFC822Value forKey:dateKey];
        }
        [reformattedData addObject:newDict];
    }
    *mappableData = reformattedData;
}
于 2011-07-18T06:25:04.983 回答