正如問題標題中提到的,由於某些原因,在檢查sqlite數據庫時,關係設置不正確。RestKit導入JSON不會設置關係
我正在導入兩個資源(書籍和章節),每個資源都在一個一對多結構的JSON文件中。這是一個例子JSON:
books.json: [ { "id": 1, "number": 12345, "name": "Book 1" } ]
chapters.json: [ { "id": 1, "bookId": 1, "name": "Chapter 1" } ]
我已經設置了以下映射:
RKEntityMapping *bookMapping = [RKEntityMapping mappingForEntityForName:@"Book"
inManagedObjectStore:managedObjectStore];
bookMapping.identificationAttributes = @[ @"id" ];
[bookMapping addAttributeMappingsFromArray:[Book attributesArray]]; // [@"id", @"number", @"name"]
RKEntityMapping *chapterMapping = [RKEntityMapping mappingForEntityForName:@"Chapter"
inManagedObjectStore:managedObjectStore];
chapterMapping.identificationAttributes = @[ @"id" ];
[chapterMapping addAttributeMappingsFromArray:[Chapter attributesArray]]; // [@"id", @"bookId", @"name"]
,當然還有連接:
[chapterMapping addConnectionForRelationship:@"book" connectedBy:@{ @"bookId": @"id" }];
這裏是導入兩個JSON的一部分文件:
RKManagedObjectImporter *importer = [[RKManagedObjectImporter alloc] initWithManagedObjectModel:managedObjectStore.managedObjectModel storePath:path];
NSString *bookJsonPath = [NSString stringWithFormat:@"%@/%@/books.json", [self getDocumentsPath], @"seeds"];
[importer importObjectsFromItemAtPath:bookJsonPath
withMapping:bookMapping
keyPath:nil
error:&error];
// [[importer managedObjectContext] saveToPersistentStore:&error];
NSString *chapterJsonPath = [NSString stringWithFormat:@"%@/%@/chapters.json", [self getDocumentsPath], @"seeds"];
[importer importObjectsFromItemAtPath:chapterJsonPath
withMapping:chapterMapping
keyPath:nil
error:&error];
success = [importer finishImporting:&error];
if (success) {
[importer logSeedingInfo];
NSLog(@"Finished seeding!");
}
導入過程完全正常,但書籍外鍵列中的章節全部爲NULL。日誌還顯示:
Caching instances of Entity 'Book' by attributes 'guid'
Imported 551 objects from file at path ... (books)
Caching instances of Entity 'Chapter' by attributes 'guid'
Imported 1908 objects from file at path ... (chapters)
Starting 1908 connection operations ...
A seed database has been generated
哪種指示它開始創建連接,但什麼也沒有發生。
更新14年12月15日: 的兩個主要錯誤是:
- 我使用了保留關鍵字
id
爲(而不是說)屬性和 - 我有一個在我的外鍵映射中犯了一個愚蠢的錯誤!在章節中出現的外鍵是
book
,我的映射預期爲bookId
。尷尬!我改變了服務器,正確地返回bookId
作爲外鍵,現在它工作。
這種方式只有連接是足夠的!無需添加RKRelationShipMappings。
謝謝你用'id'字段指出我的錯誤。我仔細檢查了我的屬性映射,並將其重命名爲「guid」。現在它的工作! – codepushr 2014-12-13 17:34:59