RestKit: Connecting Non-Nested Relationships Using

2019-09-01 15:05发布

问题:

I am trying to map objects from two separate json files (while seeding an sqlite db with RestKit). The files are connected by a foreign id file1Code.

The structure looks like this:

File 1:

[ {
  "code": "1",
  "activ": false,
  "name": "Joe"
  },
  {
  "code": "2",
  "activ": false,
  "name": "John"
  }
]

File 2:

[
  {
  "code": 666000,
  "name": "Hausarzt",
  "file1Code": "1",
  "activ": false
  }
]

Entity for File 1 looks like this:

@interface File1Entity :  KeyTab  

Entity for File 2 looks like this:

@interface File2Entity :  KeyTab
    @property (nonatomic, retain) File1Entitiy *file1Obj;

    // Transient
    @property (nonatomic, retain) NSNumber *file1Code;

KeyTab (from which both inherit) looks like this:

@interface KeyTab :  NSManagedObject
    @property (nonatomic, retain) NSNumber * code;
    @property (nonatomic, retain) NSString * name;
    @property (nonatomic, retain) NSNumber * activ;        

Now I am trying to use the "Connecting Non-Nested Relationships Using Foreign Keys" from the RestKit documentation found here.

I am using addConnectionForRelationship like this:

[file2EntityMapping addConnectionForRelationship:@"file1Obj" 
    connectedBy:@{@"file1Code": @"code"}];

But get the error message "Cannot connect relationship: invalid attributes given for source entity" since file1Obj is a property and not an attribute.

Is this the right way to do this in RestKit?

回答1:

You need to add file1Code as a transient attribute on File2Entity and set it during the mapping. The foreign key connection is completed after the mapping so the original JSON is no longer available (hence the error that the data doesn't exist).