使用Core Data和AFIncrementalStore时重新格式化JSON属性

时间:2013-05-28 21:28:15

标签: ios ruby-on-rails core-data afincrementalstore

我的iOS应用程序与此处构建的应用程序非常相似:https://devcenter.heroku.com/articles/ios-core-data-buildpack-app - 即核心数据 AFIncrementalStore ,但是使用自定义Rails 3.1服务器提供JSON。

我有两个性质相似的问题:

  • Rails有一个名为id的属性,但这是Objective-C中的保留字,所以我想在iOS应用中将其重命名为activityId或类似内容。我应该在代码中的哪个位置执行id - > activityId翻译?
  • 我的所有日​​期字段目前在iOS应用中显示为(null),我怀疑这是由于Rails格式化日期的方式(例如"2012-09-14T11:32:09+02:00")。我应该在iOS代码中添加自己的日期解析器吗?

如果可能的话,我想避免在服务器端生成自定义JSON。

谢谢!

1 个答案:

答案 0 :(得分:1)

在AFIncrementalStore的Github中的“Basic Example”之后,我将Rails属性映射到attributesForRepresentation:ofEntity:fromResponse:

的核心数据
- (NSDictionary *)attributesForRepresentation:(NSDictionary *)representation
                                     ofEntity:(NSEntityDescription *)entity
                                 fromResponse:(NSHTTPURLResponse *)response 
{
    NSMutableDictionary *mutablePropertyValues = [[super attributesForRepresentation:representation ofEntity:entity fromResponse:response] mutableCopy];
    if ([entity.name isEqualToString:@"Activity"]) {
        [mutablePropertyValues setValue:[NSNumber numberWithInteger:[[representation valueForKey:@"id"] integerValue]] forKey:@"activityID"];
    }

    return mutablePropertyValues;
}

那就是说,我沿着这条路走下去,后来才知道没有必要,因为AFIS会为你保留这个映射。请参阅“增强型受管对象模型”部分下的this deckThis podcast详细介绍了它。

对于日期转换,它在上面的“Twitter Client”示例中使用相同的方法完成:

[mutablePropertyValues setValue:[[NSValueTransformer valueTransformerForName:TTTISO8601DateTransformerName] reverseTransformedValue:[representation valueForKey:@"created_at"]] forKey:@"createdAt"];

希望这有帮助。