使用 Realm 保存不同的类别,Swift

Saving different categories with Realm, Swift

我正在做一个财务应用程序。我正在用领域保存数据,但我无法理解一件事。用户输入后,他花了多少钱,他可以选择一个类别:Supermarket, Transport and others。所以问题是我如何按类别保存用户数据。领域模型:

class Items: Object {
    @objc dynamic var personID = UUID().uuidString
    @objc dynamic var categoryAmount = ""
    @objc dynamic var categoryName = ""

    override static func primaryKey() -> String? {
        return "personID"
    }  
}
class RealmModel {
    static let shared = RealmModel()
    private let realm = try! Realm()
    let myPrimaryKey = "Primary-Key"

    func addAmount(newItem: String) {
        let categoryAmount = realm.object(ofType: Items.self, forPrimaryKey: myPrimaryKey)
        let new = Items()
        new.personID = "My-Primary-Key"
        new.categoryAmount = newItem
    
        try! realm.write {
            realm.add(new, update: .modified)
        }
    }
    
    func updateAmount(editedItem: Items, newItem: String) {
        try! realm.write {
            editedItem.categoryAmount = newItem
        }
    }
    
    func getAmount() -> Items? {
            let amount = realm.objects(Items.self).last
            return amount
        }
    
    func setAmount(newItem: String) {
        if let data = getAmount() {
            updateAmount(editedItem: data, newItem: newItem)
        } else {
            addAmount(newItem: newItem)
        }
    }
}

按钮:

@IBAction func supermarketBTN(_ sender: Any) {
    RealmModel.shared.setAmount(newItem: "\((Double(exileAmount?.categoryAmount ?? "" ) ?? 0) + (Double(self.amountTF.text ?? "") ?? 0))")
    self.exileAmount = RealmModel.shared.getAmount()
    delegate?.updateAmount(amount: self.amountTF.text ?? "")
    dismiss(animated: true, completion: nil)
    
    }

如何使用categoryName按类别保存数据?

有 100 种不同的方法可以解决这个问题。让我在高层次上提出一种可能性。

第一个问题是更改对象的结构。你需要两个;一个存储用户,另一个存储他们的类别选择和花费的金额

class UserClass: Object {
   @objc dynamic var userId = "" //however you want to define id's
   @objc dynamic var userName = ""
}

然后

class SpentMoneyClass: Object {
   @objc dynamic var _id = UUID().uuidString
   @objc dynamic var category = ""
   @objc dynamic var byUserId = ""
   @objc dynamic var amount = 0.0
}

您的数据库将包含用户,每个用户对象都有一个 userId。当用户花钱时,创建一个新的 SpentMoneyClass 并填写属性 - 假设用户 Artim 在 Travel

上花钱
let spend = SpentMoneyClass()
spend.category = "Travel"
spend.byUserId = artimUser.userId
spend.amount = 100.00

将对象写入领域

此结构使您能够查询 Artim 花费的所有金钱、所有用户花费的所有旅行金钱以及对 Artim 花费的所有旅行金钱或特定花费金额的更精细查询 - 您可以利用聚合函数 .sum很容易得到总数:

let travelTotal: Double = realm.object(SpentMoneyClass.self)
                               .filter("byUserId == x and category == 'Travel'")
                               .sum(ofProperty: "amount")

给出 Artim 在旅行上的总支出(x = Artims 用户 ID)

*注意我省略了 MongoDB Realm 所需的主键和 _id 属性以保持长度较短