【问题标题】:RestKit Mapping array of objectsRestKit 映射对象数组
【发布时间】:2017-12-15 22:37:10
【问题描述】:

我正在使用 RestKit 进行 API 调用,但我的一个属性没有正确映射。

说我有:

// 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"
    }
  ]
}

请求已成功发出,但是当我检查映射结果时,Animal 类中的 favoriteFruits 数组中的元素不像我预期的那样属于 Fruit 类型。它们的类型为NSDictionaryNSDictionary 上的值都是正确的...我只需要将它们自动转换为 Fruit 对象...

不确定这是否相关,但是当我在调试器中尝试时:

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

我明白了:

错误:执行被中断,原因:试图取消引用无效的 ObjC 对象或向其发送无法识别的选择器。 进程已经返回到表达式求值前的状态。

感谢您的帮助。

【问题讨论】:

    标签: objective-c afnetworking restkit nscoding


    【解决方案1】:

    意识到我从未在映射中添加正确的关系...我应该做的是:

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

    然后添加这些行:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-04-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-01
      • 1970-01-01
      相关资源
      最近更新 更多