RestKit willMapData:

Den*_*nis 3 objective-c restkit

以下代码从我的服务器接收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];
    }
}
Run Code Online (Sandbox Code Playgroud)

但是,该行[dict setValue:RFC822Value forKey:dateKey];提出了一条NSUnknownKeyException消息this class is not key value coding-compliant for the key created_at.

我在这做错了什么?我的主要问题可能是我对这个inout声明感到不舒服......

Vic*_* K. 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;
}
Run Code Online (Sandbox Code Playgroud)