2017-07-11 448 views
0

我正在使用RestKit進行API調用,但其中一個屬性映射不正確。RestKit映射對象數組

說我有:

// Animal.h 
@interface Animal: NSObject 

@property (nonatomic, strong) NSArray<Fruit*> favoriteFruits; 

@end 

與實施:

// Animal.h 
// This class conforms to NSCoding and correctly implements encodeWithCoder and initWithCoder, no problem 

我也有一個Fruit類相似NSCoding東西:

// Fruit.h 
@interface Fruit: NSObject 

@property (nonatomic, strong) NSString* name; 

@end 

下面是我如何設置我的映射:

[animalMapping addAttributeMappingsFromDictionary:@{ 
    @"fruits": @"favoriteFruits" 
}]; 

當我做通過RestKit GET請求,我回來了JSON是這樣的:

{ 
    "fruits": [ 
    { 
     "name": "banana" 
    }, 
    { 
     "name: "apple" 
    } 
    ] 
} 

請求已成功建立,但是當我檢查映射結果,在favoriteFruits數組中的元素在Animal類沒有類型Fruit像我所料。他們的類型是NSDictionary。在NSDictionary的值是正確的......我只需要他們能夠自動地轉化爲Fruit對象...

不知道這是否是相關的,但是當我在調試器嘗試這樣:

(lldb) po ((Fruit*)myAnimal.favoriteFruits[0]).name 

我得到:

error: Execution was interrupted, reason: Attempted to dereference an invalid ObjC Object or send it an unrecognized selector. The process has been returned to the state before expression evaluation.

感謝您的幫助。

回答

0

意識到我從來沒有加入到映射正確關係......我應該做的是:

[animalMapping addAttributeMappingsFromDictionary:@{ 
    // Other attributes go here, but not favoriteFruits 
}]; 

然後添加這些行:

RKRelationshipMapping *fruitsRelationship = [RKRelationshipMapping relationshipMappingFromKeyPath:@"fruits" toKeyPath:@"favoriteFruits" withMapping:animalMapping]; 
[candidateMapping addPropertyMapping: fruitsRelationship];