首页 > 解决方案 > Realm Swift:对象列表不起作用

问题描述

我尝试在 Swift 中将 Realm 连接到我的食谱应用程序。我对成分有疑问:当我运行我的应用程序时,我遇到了这个错误

There must be a primary key property named '_id' on a synchronized Realm but none was found for type 'recipe_ingredients'

我认为这是因为我将成分对象键入为领域对象,并且它需要一个主键。我试图添加一个,但它说

Primary Key for class 'recipe_ingredients' has been added.

这是我的模型文件:

import RealmSwift
import Foundation

class recipe: Object {
    @Persisted(primaryKey: true) var _id: ObjectId?
    @Persisted var name: String?
    @Persisted var category: String?
    @Persisted var image: String?
    @Persisted var note: Double?
    @Persisted var likes: Int?
    @Persisted var ingredients: List<recipe_ingredients>
    @Persisted var steps: List<recipe_steps>
    @Persisted var time: String?
    @Persisted var units: Int?
    
    convenience init(name: String) {
        self.init()
        self.name = name
    }
}

class recipe_ingredients: Object{
    @Persisted(primaryKey: true) var _id: ObjectId?
    @Persisted var name: String?
    @Persisted var quantity: String?
}

class recipe_steps: Object{
    @Persisted(primaryKey: true) var _id: ObjectId?
    @Persisted var step_description: String?
    @Persisted var step: Int?
}

这是领域模式

{
  "title": "recipe",
  "properties": {
    "__v": {
      "bsonType": "int"
    },
    "_id": {
      "bsonType": "objectId"
    },
    "category": {
      "bsonType": "string"
    },
    "image": {
      "bsonType": "string"
    },
    "ingredients": {
      "bsonType": "array",
      "items": {
        "bsonType": "object",
        "properties": {
          "name": {
            "bsonType": "string"
          },
          "quantity": {
            "bsonType": "string"
          }
        }
      }
    },
    "likes": {
      "bsonType": "int"
    },
    "name": {
      "bsonType": "string"
    },
    "note": {
      "bsonType": "double"
    },
    "steps": {
      "bsonType": "array",
      "items": {
        "bsonType": "object",
        "properties": {
          "description": {
            "bsonType": "string"
          },
          "step": {
            "bsonType": "int"
          }
        }
      }
    },
    "time": {
      "bsonType": "string"
    },
    "units": {
      "bsonType": "int"
    }
  }
}

谢谢你的帮助 !

标签: iosswiftmongodbrealm

解决方案


推荐阅读