2013-12-12 36 views
1

我有一個JSON結構retreived通過網絡套接字,我想應用到現有的管理對象。要修改的特定對象由JSON中的一個鍵標識。 JSON可能不包含所有屬性,但我只想更新JSON中存在的屬性(不會使其他屬性無效)。RestKit:如何使用RKMappingOperation

我在RestKit IRC頻道上得到了一些使用RKMappingOperation的初始指針,但我現在停留在實現上。

首先我嘗試這樣做:

 RKMappingOperation *mappingOperation = [[RKMappingOperation alloc] initWithSourceObject:parsedObject destinationObject:nil mapping:[MyManagedObjectClass customMapping]]; 

因爲我沒有對象的實例手頭更新,我通過零至destinationObject,跳頻映射器根據映射會看着辦吧提供。

唉,在執行映射(但沒有錯誤)後,我從mappingOperation的mappingInfo得到零。

 [mappingOperation performMapping:&localError]; 

     if (localError != nil) { 
      NSLog(@"%@", [mappingOperation mappingInfo]); // outputs nil 
     } else { 
      NSLog(@"error: %@", localError); // no error 
     } 

所以我的直覺是,我確實需要得到我想要更新管理對象實例,並將其提供給映射操作,但我無法弄清楚如何。我嘗試在託管對象上下文上使用existingObjectWithID,並將ID傳遞給我的JSON,但沒有運氣。當把它傳遞給映射操作時,我得到一個'null'錯誤。

我在正確的軌道上嗎?我錯過了什麼?

編輯:擺弄一些更多後,我意識到文檔指定,如果destinationObject設置爲零,您必須提供一個數據源。因此,這裏是我的嘗試下一個:

 RKManagedObjectMappingOperationDataSource *mappingDS = [[RKManagedObjectMappingOperationDataSource alloc] initWithManagedObjectContext:[[[RKObjectManager sharedManager ] managedObjectStore] mainQueueManagedObjectContext] cache:[[[RKObjectManager sharedManager] managedObjectStore] managedObjectCache]]; 
     mappingOperation.dataSource = mappingDS; 

尷尬,我也混了錯誤的條件,所以這就是爲什麼我看不到在剛纔嘗試錯誤(沒有數據源)。現在看起來映射操作成功執行了。將報告回來,如果它實際上的情況,並回答我的問題:-)

回答

3

解決辦法:

RKMappingOperation *mappingOperation = [[RKMappingOperation alloc] initWithSourceObject:parsedObject destinationObject:nil mapping:[MyManagedObjectClass customMapping]]; 

RKManagedObjectMappingOperationDataSource *mappingDS = [[RKManagedObjectMappingOperationDataSource alloc] initWithManagedObjectContext:[[[RKObjectManager sharedManager ] managedObjectStore] mainQueueManagedObjectContext] cache:[[[RKObjectManager sharedManager] managedObjectStore] managedObjectCache]]; 
mappingOperation.dataSource = mappingDS; 

[mappingOperation performMapping:&localError]; 

    if (localError != nil) { 
     NSLog(@"%@", [mappingOperation mappingInfo]); 
    } else { 
     NSLog(@"error: %@", localError); 
    } 
+0

感謝分享解決方案!這就是我一直在尋找的東西。對我來說,RKObjectMappingOperationDataSource實際上是我尋找的那個,因爲我不需要CoreData。 – Ben