【问题标题】:How to append list property of an object Realmswift如何附加对象Realmswift的列表属性
【发布时间】:2020-07-16 00:10:00
【问题描述】:

我有两门课:

第一个:

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 个 GamesObject,其中每个包含两个 GameObject 列表。我想通过删除以下行

realm.add(games)

只会将游戏附加到列表属性,并避免添加游戏对象。为了让它工作,我错过了什么?

感谢阅读。

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?那为什么还要GamesObject呢?您可以在 Realm 中拥有一堆 GameObjects,然后通过执行 realm.objects(GameObject.self) 获得所有这些。是否会有多个 GamesObjects 包含不同的 GameObjects
  • 因为我会为我的 sessionOFGames 做一个列表。从阅读中我必须制作 3 个类,因为 real 不支持多维数组。
  • 据我了解:每次出现AddGameViewController 时,都应创建一个新的GamesObject 并将其添加到领域,并且该VC 上的添加游戏按钮应仅将游戏添加到该@ 987654335@。我理解正确吗?
  • 我的逻辑是:GamesObject 永远只有一个对象。因为我有一个保存会话按钮,当按下它时,我会抓取GamesObject 的内容,将其附加到另一个列表中,该列表将是一个“会话对象”并保存它。保存后,我从gameObject 中删除该对象。并重新启动。但就我的问题而言,您的回答是正确的。我正在用领域尝试不同的东西。

标签: ios swift realm realm-list


【解决方案1】:

您的代码会产生这种行为,因为添加按钮每次都会将新的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)")
        }
    }

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-31
    • 2012-05-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-03
    • 1970-01-01
    相关资源
    最近更新 更多