2017-07-11 450 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];