Saving different categories with Realm, Swift

I'm doing a finance app. I'm saving data with realm, but i can't understand one thing. After the user entered, how much money he spent, he can choose a category: Supermarket, Transport and others. So the question is how can i save user's data by categories. RealmModel:

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

Button:

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

How should I use categoryName to save data by categories?



Read more here: https://stackoverflow.com/questions/64952966/saving-different-categories-with-realm-swift

Content Attribution

This content was originally published by Artem Trefilov at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.

%d bloggers like this: