2012-04-29 128 views
12

RestKit可以連接關係而不將外鍵存儲爲屬性,即直接來自JSON中的鍵路徑?RestKit對象與外鍵的映射關係

特別是,我有一個工作has_many房關係。房間的JSON不包含作業,而是兩者分別加載:

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

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

作業在房間之前加載。

我CoreData模型,工作有

@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"]; 

我在想,如果有一種方法,我可以做到這一點沒有額外的作業ID屬性?我不想在CoreData xcdatamodeld中有一個jobID屬性 - 它是多餘的,因爲關係覆蓋了這個屬性。

此外,如果我重建NSManagedObjects,我需要重新添加jobID屬性,這是乏味的。我不能通過JSON中的job_id keypath來告訴restkit將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". 
+0

您是否已經發現如何正確連接核心數據中的關係,而沒有在真實關係旁邊具有冗餘ID屬性? – thejaz 2013-05-24 14:24:32

回答

5

我會做的JobId核心數據的瞬時值,並編寫自定義設置和獲取它。

的集將設置關係self.job = methodToReturnObjectMatchingJobId(這可以由其他套件配合使用)

如果你不使用mogenerator的get將返回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的對象。

+0

這不會使Restkit的關係映射變得多餘嗎?我應該禁用Restkit的映射,還是讓setClaimId保持空白? – geon 2013-03-08 10:54:49

+0

我正在做的是使用映射或claimId並使用它將關係設置爲在restKit之外聲明對象。因此,在這種情況下,您不會在restKit中爲關係創建映射(如果這是您的工作方式)。 – 2013-03-10 13:25:39