【问题标题】:Realm objective c - array of array领域目标 c - 数组数组
【发布时间】:2016-05-09 07:46:07
【问题描述】:

我的产品 json 中有这个功能。它只是字符串列表。但是,它们必须本地化。所以,它变成了数组数组。

我无法在 Realm 中执行 Array of Array。任何人都可以建议我如何在 Realm Objective-C 中实现这一点?

{
 "name" : "Product 1",
 "features" : [
 [
  { "locale" : "en", value : "feature1"},
  { "locale" : "cn", value : "feature1 in cn"}
 ],
 [
  { "locale" : "en", value : "feature2"},
  { "locale" : "cn", value : "feature2 in cn"}
 ]
]
}

谢谢

【问题讨论】:

    标签: objective-c arrays realm


    【解决方案1】:

    通过稍微修改您的 JSON,无论是在源代码中还是作为代码中映射步骤的一部分,您都可以将其直接传递给 Realm 的 KVC 初始化机制:

    {
      "name": "Product 1",
      "features": [
        [[
          { "locale": "en", "value": "feature1" },
          { "locale": "cn", "value": "feature1 in cn" }
        ]],
        [[
          { "locale": "en", "value": "feature2" },
          { "locale": "cn", "value": "feature2 in cn" }
        ]]
      ]
    }
    

    映射到这些领域模型:

    @interface Feature : RLMObject
    @property NSString *locale;
    @property NSString *value;
    @end
    @implementation Feature
    @end
    
    RLM_ARRAY_TYPE(Feature);
    
    @interface FeatureList : RLMObject
    @property RLMArray<Feature> *features;
    @end
    @implementation FeatureList
    @end
    
    RLM_ARRAY_TYPE(FeatureList);
    
    @interface Product : RLMObject
    @property NSString *name;
    @property RLMArray<FeatureList> *features;
    @end
    @implementation Product
    @end
    

    此时,您可以将 JSON 反序列化为字典并使用以下命令初始化您的 Realm 对象图:

    NSDictionary *productDictionary = [NSJSONSerialization JSONObjectWithData:[NSData dataWithContentsOfURL:[[NSBundle mainBundle] URLForResource:@"product" withExtension:@"json"]] options:0 error:nil];
    [Product createInDefaultRealmWithValue:productDictionary];
    

    它为您提供以下对象图:

    [0] Product {
      name = Product 1;
      features = RLMArray <0x7fe43366be00> (
        [0] FeatureList {
          features = RLMArray <0x7fec3a772c10> (
            [0] Feature {
              locale = en;
              value = feature1;
            },
            [1] Feature {
              locale = cn;
              value = feature1 in cn;
            }
          );
        },
        [1] FeatureList {
          features = RLMArray <0x7fec3a773d20> (
            [0] Feature {
              locale = en;
              value = feature2;
            },
            [1] Feature {
              locale = cn;
              value = feature2 in cn;
            }
          );
        }
      );
    }
    

    【讨论】:

    • 我应该把featureLists放在json的什么地方?
    • 我已更新我的答案以反映您对问题的最新编辑
    • 我们可以改变 Realm 模型端而不是 json 吗?
    • 因为 json 来自 api。其他平台使用这个 json 有点奇怪,因为它针对领域进行了优化。
    • 我建议你使用像 Mantle 或 KZPropertyMapper 这样的模型映射框架
    猜你喜欢
    • 1970-01-01
    • 2016-03-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多