核心数据 – RestKit对象与外键的映射关系

RestKit可以连接一个关系而不将外键存储为一个属性,即直接从JSON中的关键字?

特别是,我有一个Job has_many客房关系.房间的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(非原子,强)NSNumber * jobID;到房间,我@合成.

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将房间连接到相应的作业?

如果我删除属性,mapKeyPath:@“job_id”行,并将最后一行更改为[mapping connectRelationship:@“job”withObjectForPrimaryKeyAttribute:@“job_id”];我得到

the entity Room is not key value coding-compliant for the key "job_id".
最佳答案
我将使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返回对象的简单查询.

转载注明原文:核心数据 – RestKit对象与外键的映射关系 - 代码日志