如何附加对象 Realmswift 的列表 属性

How to append list property of an object Realmswift

我有两个 类 :

第一个:

class GameObject: Object {
    @objc dynamic var gameOutcome: String? = nil
    @objc dynamic  var Goal : Int = 0

}

第二个:

 class GamesObject: Object {
    let games = List<GameObject>()
}

在 addGameVC 上,我添加了一个游戏,将其保存在具有领域的 GameObject 上,并在写入中将游戏附加到列表 属性。我的目标是让 GamesObject 包含所有添加游戏的列表。这样我就可以在 TableView 上显示它们。但是,当我添加例如两个游戏时,我得到的是 2 个 GameObject,包括每个游戏对象的两个列表。我想通过删除以下行

realm.add(games)

只会将游戏附加到列表 属性 并且会避免添加 gamesObject。我错过了什么才能让它发挥作用?

感谢阅读。

class AddGameViewController: UIViewController{
        

        let realm = try! Realm()
         var realmGame = GameObject()
        let gamesList = GamesObject()

     @IBAction func addButtonPressed(_ sender: UIButton) {
         realmGame.gameOutcome = matchOutcome
         realmGame.goal = (Int(goal.text!) ?? 0)
         saveOnRealm(games: gamesList, game: realmGame)
    }

    
    func saveOnRealm(games: GamesObject, game: GameObject){
        do {
            try realm.write {
                
                games.gamess.append(game)
                realm.add(game)
                realm.add(games)
                
            }
        } catch {
            print("error \(error)")
        }
    }

}

您的代码会产生此行为,因为添加按钮每次都会向领域中添加一个新的 GamesObject。要解决此问题,如果这是您第一次添加游戏,则只需将 GamesList 放入 Realm。

您还应该在每次按下添加按钮时创建一个新的 GameObject

class AddGameViewController: UIViewController{
    let realm = try! Realm()
    let gamesList = GamesObject()

    @IBAction func addButtonPressed(_ sender: UIButton) {
        let realmGame = GameObject() // I moved realmGame inside the button action
        realmGame.gameOutcome = matchOutcome
        realmGame.goal = (Int(goal.text!) ?? 0)
        saveOnRealm(game: realmGame)
    }

    
    func saveOnRealm(game: GameObject){
        do {
            try realm.write {
                if gamesList.gamess.isEmpty { // first time
                    realm.add(gamesList)
                }
                gamesList.gamess.append(game) // this also adds game into realm
                
            }
        } catch {
            print("error \(error)")
        }
    }

}