2013-10-21 56 views
0

我有一個JSON數據結構進行排序如何在RestKit 0.20中實現`hasOne:withMapping:`?

{ 
    "id": "8a1a39479d03d959", 
    "sortOrder": 3, 
    "timestamp": 1381669499.11, 
} 

,並剛好有一個項目的另一個文件結構的項目:

{ 
    "id": "d88e3c3d1630db4c", 
    "item": "8a1a39479d03d959", 
    "timestamp": 1381669505.364, 
    "version": 2 
} 

我一直在努力獲得這種映射到工作,直到我添加了一個[files]到項目JSON列表只是爲了映射關係。但是,讀取舊的post on the Google group,我看到它理應使用有可能這樣這些關係映射(未測試的代碼,只是意譯上面的鏈接):

RKManagedObjectMapping *itemMapping = [RKManagedObjectMapping mappingForClass:[Item class]]; 
itemMapping.primaryKeyAttribute = @"itemID"; 
[itemMapping mapKeyPath:@"sortOrder" toAttribute:@"sortOrder"]; 
[itemMapping mapKeyPath:@"id" toAttribute:@"itemID"]; 

RKManagedObjectMapping *fileMapping = [RKManagedObjectMapping mappingForClass:[File class]]; 
fileMapping.primaryKeyAttribute = @"fileID"; 
[fileMapping mapKeyPath:@"id" toAttribute:@"fileID"]; 
[fileMapping mapKeyPath:@"item" toAttribute:@"itemID"]; 
[fileMapping mapKeyPath:@"version" toAttribute:@"version"]; 

[fileMapping hasOne:@"item" withMapping:itemMapping]; 
[fileMapping connectRelationship:@"organization" withObjectForPrimaryKeyAttribute:@"itemID"]; 

然而hasOne:withMapping:不存在任何更RestKit 0.20。現在,如何將一個一對多關係與在JSON中作爲簡單字符串返回的標識符進行映射,這種正確的方法是什麼?僅供參考,我在此項目中使用CoreData集成。

+0

注意,如果引用的代碼示例從0.10.x開始,而不是0.2x,所以它沒有什麼意義......你要找的是'外鍵映射'。 – Wain

+0

@Wain感謝您的編輯。我完全意識到代碼示例是從0.10開始的,這就是爲什麼我要問如何在0.20中做同樣的事情! – DaGaMs

+0

但是您已經轉換了大部分映射,這只是您需要幫助的關係? – Wain

回答

1

好的,您的映射將項目標識設置爲identifier。在文件上這不對應 - 它需要。添加一個瞬態屬性並將item映射到它(我們稱之爲itemIdentifier)。現在,你可以設置一個映射關係中的核心數據的關係,以填補(這應該是雙向的,我假設item < < - >files):

[fileMapping addConnectionForRelationship:@"item" connectedBy:@{ @"itemIdentifier": @"identifier" }]; 
+0

就是這樣!非常感謝,我沒有意識到我必須創建一個瞬態屬性才能使它工作! – DaGaMs

0

試試這個:

RKEntityMapping *mapping = [RKEntityMapping mappingForEntityForName:@"Item" 
               inManagedObjectStore:[YourManagedObjectStore]; 
[mapping addAttributeMappingsFromDictionary:@{ 
               @"sortOrder": @"sortOrder", 
               @"id":@"itemID" 
               }]; 

mapping.identificationAttributes = @[@"itemID"]; 

[mapping addRelationshipMappingWithSourceKeyPath:@"organization" 
             mapping:fileMapping]; 

我希望它能幫助。

+0

有趣的,所以你說如果我有一對多的關係'Item <---- organization- --- >> File',我必須添加關係映射到「itemMapping」?我的問題是:我如何設置「fileMapping」,以便正確設置Item和File之間的CoreData關係? – DaGaMs

+0

好吧,我只是測試了這一點;不幸的是,它不起作用,即關係沒有設置,而所有其他映射工作正常。 – DaGaMs

+0

這裏使用的關係類型是嵌套的JSON(即直接的,而不是外鍵)。 – Wain