【问题标题】:Nesting arrays in Realm with Swift使用 Swift 在 Realm 中嵌套数组
【发布时间】:2018-10-15 11:56:51
【问题描述】:

我已经阅读了几个关于如何将数据数组存储到 Realm 的示例。不过,我还没有找到一个特别清楚的例子。

简而言之,我有一个(简化的)JSON,如下所示,我想将其存储在 Realm 中。如何向 Realm 添加一系列成分,使其包含在 menuItems 数组中?

{
   "menuItems": [
      {
         "name": "name 1",
         "ingredients": ["ingredient 1", "ingredient 2"]
      },
      {
         "name": "name 2",
         "ingredients": ["ingredient 1", "ingredient 2", "ingredient 3"
         ]
      }
   ]
}

我的领域模型设置如下:

class MenuItemsRealm: Object {

    @objc dynamic var name: String = ""
    var ingredients = List<IngredientItemsRealm>()
}

class IngredientItemsRealm: Object {

    @objc dynamic var ingredientItem: String = ""
} 

【问题讨论】:

    标签: json swift realm nsarray


    【解决方案1】:

    在您的 JSON 中,您声明 menuItem 对象有一个名为 ingredients 的属性/变量,它包含一个 String 数组。您可能想要做的是创建一个对象数组,其中包含特定的ingredientItem 属性/变量。

    为了举例说明您的 JSON,应该是这样的:

    {
       "menuItems": [
          {
             "name": "name 1",
             "ingredients": [
                 {
                     "ingredientItem": "item name"
                 }
             ]
          }
       ]
    }
    

    【讨论】:

      猜你喜欢
      • 2016-12-31
      • 2020-08-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多