RestKit对象映射与外键的关系

时间:2012-04-29 07:48:55

标签: core-data restkit

RestKit是否可以连接关系而不将外键存储为属性,即直接来自JSON中的keypath?

特别是,我有一个Job has_many Rooms的关系。房间的JSON不包含作业,而是两者都单独加载:

- job: {
    id: 1,
    name: "John"
}

- room: {
    id: 4,
    job_id: 1,
    name: "spare bedroom"
}

作业在会议室之前加载。

我的CoreData模型,Job具有

的属性
@interface Job : NSManagedObject
@property (nonatomic, retain) NSNumber * identifier;
@property (nonatomic, retain) NSString * name;
@property (nonatomic, retain) NSSet *rooms;
@end

@interface Room : NSManagedObject
@property (nonatomic, retain) NSNumber * identifier;
@property (nonatomic, retain) NSString * name;
@property (nonatomic, retain) Job *job;
@end

目前我向房间添加了@property (nonatomic, strong) NSNumber *jobID;,我@synthesize

JobMapping:
    mapping = [RKManagedObjectMapping mappingForClass:[Job class]];
    [mapping setPrimaryKeyAttribute:@"identifier"];

    [mapping mapAttributes:@"name", nil];
    [mapping mapKeyPath:@"id" toAttribute:@"identifier"];

    [mapping mapRelationship:@"rooms" withMapping:[Room objectMapping]];



RoomMapping
    mapping = [RKManagedObjectMapping mappingForClass:[Room class]];
    [mapping setPrimaryKeyAttribute:@"identifier"];

    [mapping mapAttributes:@"name", nil];
    [mapping mapKeyPath:@"id" toAttribute:@"identifier"];
    [mapping mapKeyPath:@"job_id" toAttribute:@"jobID"];

    [mapping mapRelationship:@"job" withMapping:[Job objectMapping]];

    [mapping connectRelationship:@"job" withObjectForPrimaryKeyAttribute:@"jobID"];

我想知道是否有一种方法可以在没有额外的jobID属性的情况下做到这一点?我不想在CoreData xcdatamodeld中有一个jobID属性 - 它是多余的,因为关系涵盖了

另外,如果我重建NSManagedObjects,我需要重新添加jobID属性,这很乏味。我不能告诉restkit通过JSON中的job_id keypath将Room连接到相应的Job吗?

如果我移除了mapKeyPath:@"job_id"行的属性,并将最后一行更改为[mapping connectRelationship:@"job" withObjectForPrimaryKeyAttribute:@"job_id"];

the entity Room is not key value coding-compliant for the key "job_id".

1 个答案:

答案 0 :(得分:5)

我会将JobId作为核心数据中的瞬态值,并编写一个自定义集并获取它。

该集合将关系设置为self.job = methodToReturnObjectMatchingJobId (这将由休息工具包使用)

get将返回self.job.identifier

如果您不使用mogenerator,我建议您查看它以满足您的所有核心数据需求。

下面是我如何做到的示例代码:

-(void) setClaimId:(NSNumber *)claimId{
     Claim *propertyClaim=[Claim listItemFromId:[claimId intValue] withContext:self.managedObjectContext]; 

    self.claim=propertyClaim; 
}
-(NSNumber*) claimId{

  return self.claim.referenceId;
}

其中listItemFromId是一个基于id返回对象的简单查询。