Issue with adding a one-to-one foreign-key connection to a RestKit mapping

大憨熊 提交于 2019-12-25 01:36:14

问题


I am trying to add a connection to a RestKit mapping but without success.

My JSON is as follows:

{
  parent: {
    token: "token"
    title: "title",
    description: "description",
    child_id: 1
  }
}

My CoreData scheme defines that the Parent ManagedObject has a Child relation under the child key (and the opposite). The Parent mapping happens after I already have a corresponding Child object in CoreData, so that's not a problem.

I followed some links and discussions around the web in order to solve this, but none work. What is the right way to do this, without having to add a child_id property to Parent (some people claimed they did this but it looks wrong to me).

Assuming I have this mapping:

- (RKEntityMapping *)parentResponseMapping {
    RKEntityMapping *mapping = [RKEntityMapping mappingForEntityForName:@"Parent" inManagedObjectStore:[self myStore]];
    [mapping addAttributeMappingsFromArray:@[@"title", @"description"]];
    mapping.identificationAttributes = @[@"token"];
    return mapping;
}

At first I tried adding the connection like this:

NSEntityDescription *parentEntity = [NSEntityDescription entityForName:@"Parent" inManagedObjectContext:[self myContext]];
NSRelationshipDescription *childRelationship = [parentEntity relationshipsByName][@"seller"];
RKConnectionDescription *connection = [[RKConnectionDescription alloc] initWithRelationship:childRelationship keyPath:@"child_id"];

[mapping addConnection:connection];

But I got an error that child_id is not a valid attribute (this is where I tried adding the child_id property to my scheme but again, that seems messy to me, and besides, it didn't work).

I also tried adding the connection by:

[addConnectionForRelationship:@"child" connectedBy:@"child_id"]

But this didn't work either.

Both these methods ignore the child mapping anyway.

What is the right way to achieve this?

EDIT: RestKit Object Mapping relationships with foreign keys - This was answered here already but the solution looks odd to me. Is this the only way to do this?


回答1:


without having to add a child_id property to Parent (some people claimed they did this but it looks wrong to me).

This is actually the right way to do it...

The point is the RestKit needs some way to map the two items together, some key with which to search and find the items to connect. This information only needs to be transient (assuming you are loading the data in one go or the other side of the identification is a persistent attribute). There isn't really another way to do it.



来源:https://stackoverflow.com/questions/16651725/issue-with-adding-a-one-to-one-foreign-key-connection-to-a-restkit-mapping

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