更新领域列表会删除其他名称

问题描述 投票:0回答:2

我正在尝试更新领域列表,但出于某种原因,它删除了最后一个,而只添加了新的。

这就是我在做的事情:

if !RealmService.shared.ifPortfolioExists(name: newPortfolio.name){//Check if portfolio with given name already exists
            newPortfolio.transactions.append(newTransaction)//Add new transaction to the portfolio's transactions list
            newTransaction.portfolio = newPortfolio//Link portfolio to transaction

            RealmService.shared.create(newPortfolio)
            RealmService.shared.create(newTransaction)

        }else{
            newPortfolio.transactions.append(newTransaction)
            newTransaction.portfolio = newPortfolio
            RealmService.shared.create(newTransaction)

        }

这是创建功能:

func create<T: Object>(_ object: T){
        do {
            try realm.write{
                realm.add(object, update: true)
            }
        } catch {
            post(error)
        }
    }

我也有文件中提到的primaryKeys()

我做错了什么,有人可以解释一下吗?

swift realm
2个回答
0
投票

根据Realm class description,对象必须有一个主键才能使更新生效。既然你没有提到这一点,我认为你的领域对象缺乏它。

如果对象具有主键,则仅传递true以进行更新。如果Realm中没有对象具有相同的主键值,则插入该对象。否则,使用任何更改的值更新现有对象。


0
投票

解决方案是我必须首先获得所有当前的。

这是我应用的逻辑:

let currentTransactions = RealmService.shared.realm.objects(Transaction.self).filter("portfolio_name = '\(selectedPortfolioName)'")
        if !RealmService.shared.ifPortfolioExists(name: newPortfolio.name){
            for transaction in currentTransactions{
                newPortfolio.transactions.append(transaction)
            }
            newPortfolio.transactions.append(newTransaction)
            newTransaction.portfolio = newPortfolio

            RealmService.shared.create(newPortfolio)
            RealmService.shared.create(newTransaction)

        }else{
            for transaction in currentTransactions{
                newPortfolio.transactions.append(transaction)
            }
            newPortfolio.transactions.append(newTransaction)
            newTransaction.portfolio = newPortfolio
            RealmService.shared.create(newTransaction)

        }
© www.soinside.com 2019 - 2024. All rights reserved.