Where to put object mappings (in RestKIt)

偶尔善良 提交于 2019-12-22 05:53:39

问题


As I don't want to hijack another thread here comes my question about mappings.

First read: Where's the best place to put object mappings in RestKit

I'm sure that the answer Blake Waters gave will probable be very correct as he is a much smarter and more experienced guy than I am, but to me logic tells me to put the mapping in each model: if you change something in your model, you're just a scroll away to change your mappings.

In my AppDelegate I would then just call the initMappings (or whatever you want to call it) in each of my models.


回答1:


I'm also a fan of placing the mappings with my models. I do it by adding a class method to each model so I can get the mapping whenever/wherever I need it.

+ (RKObjectMapping *)objectMapping 
{
    RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[self class]];

    [mapping mapKeyPath:@"Id"       toAttribute:@"id"];
    [mapping mapKeyPath:@"Subject"      toAttribute:@"subject"];
    [mapping mapKeyPath:@"Message"      toAttribute:@"message"];
    [mapping mapKeyPath:@"PostDate"     toAttribute:@"postDateStr"];
    [mapping mapKeyPath:@"StatusId"     toAttribute:@"statusId"];
    [mapping mapKeyPath:@"StatusDate"   toAttribute:@"statusDateStr"];

    mapping.setNilForMissingRelationships = YES;

    return mapping;
}



回答2:


I've chosen the route of creating a category and put it in there. I've created it on my app delegate class instead than the mapping provider though.

I think the problem with having it in the models is just like described in the other thread, if you have relations you might end up with circular references.




回答3:


I believe that is very natural to think the way you do, it has sense as you have more control over the code and its cleaner, but you have to be very careful, as many have said, the problem with circular references can be a big trouble.

A solution on that issue is that when you have an A entity referring to B, and B to A, then in one of both entities you will have to choose not to map directly the entity or you will end in a loop.

When you have everything on the same scope, defining circular references becomes imposible because you need the initial definition of B to add it's reference on A, so the solution I just mentioned is the natural way of doing it on this approach.

It depends on you and your app which approach do you want to use, which is better for you and your team to adopt. You have to choose between posible errors vs cleaner code.



来源:https://stackoverflow.com/questions/7399095/where-to-put-object-mappings-in-restkit

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!