RestKit是否可以在不将外键存储为属性的情况下(即直接从JSON中的键路径存储)连接关系?
特别是,我有一个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
目前,我在Room中添加了一个
@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 key 路径将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".
最佳答案
我将JobId设为核心数据中的 transient 值,并编写一个自定义集并获取它。
该集合会将关系设置为self.job = methodToReturnObjectMatchingJobId(这将由rest kit使用)
获取将返回self.job.identifier
如果您不使用发电机,我建议您看看它是否满足所有核心数据需求。
下面是我如何做到的示例代码:
-(void) setClaimId:(NSNumber *)claimId{
Claim *propertyClaim=[Claim listItemFromId:[claimId intValue] withContext:self.managedObjectContext];
self.claim=propertyClaim;
}
-(NSNumber*) claimId{
return self.claim.referenceId;
}
其中listItemFromId是一个简单查询,该查询根据ID返回对象。
关于core-data - RestKit与外键的对象映射关系,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/10370562/