iosswiftrealmrealm-list

How to append list property of an object Realmswift


I have two classes :

First One:

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

}

Second One:

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

On the addGameVC, I add a game save it on the GameObject with realm and appending the game to the list property within a write. My goal is to have a GamesObject including a list of all added game(s).So I can display them on a TableView. However when I add for example two games, what I get is 2 GamesObject, including each of them two list of GameObject. I thought by removing the following line

realm.add(games)

would only append the game to the list property and would avoid adding a gamesObject. What am i missing it order to make it work ?

Thanks for reading. enter image description here

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)")
        }
    }

}

Solution

  • Your code produces this behaviour because the add button will add a new GamesObject into realm every time. To fix this, you need to only put the GamesList into Realm if it is the first time you are adding a game.

    You should also create a new GameObject each time you press the add button.

    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)")
            }
        }
    
    }