Search code examples
iosruby-on-railscore-dataafincrementalstore

Reformatting JSON attributes when using Core Data and AFIncrementalStore


I have an iOS app quite similar to the one built here: https://devcenter.heroku.com/articles/ios-core-data-buildpack-app - i.e. Core Data and AFIncrementalStore, but with a custom Rails 3.1 server which serves JSON.

I have two problems of similar nature:

  • Rails has an attribute named id, but this is a reserved word in Objective-C, so I'd like to rename it to activityId or similar in the iOS app. Where in the code should I perform this id -> activityId translation?
  • All my date fields currently show up as (null) in the iOS app, which I suspect is due to Rails way of formatting dates (e.g. "2012-09-14T11:32:09+02:00"). Where in the iOS code should I add my own date parser?

I'd like to avoid custom JSON generation on the server side, if possible.

Thanks!


Solution

  • Following the "Basic Example" from AFIncrementalStore's Github, I mapped Rails attributes to Core Data's at 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;
    }
    

    That said, I went down that path and learned later that it is not necessary because AFIS keeps that mapped for you. See this deck under the section 'Augmented Managed Object Model'. This podcast goes over it in detail.

    As for the Date conversion, it is done in the same method above in the "Twitter Client" example:

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

    Hope this helps.