Realm writes data every time the app loads

41 views Asked by At

I'm writing an App, that takes information from an Excel document and saves the Data in Realm. My problem is, that every time I open the App, the Realm Database will save a copy of the Information. Now I get my TableViews with 3 times the same items.

Here is the code in my Main View Controller:

class ViewController: UIViewController {
    
    let realm = try! Realm()
    
    var importExcel = Import()

    
    var xslxConvert = xslxConverter()
    
    var currentString: [String] = []
    
    var Name = ""
    
    
    @IBOutlet weak var VRLabel: UIButton!
    @IBOutlet weak var configurationLabel: UIButton!
    @IBOutlet weak var Label: UILabel!
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        currentString = importExcel.Results()
        
        Label.text = Name
        
        DispatchQueue.main.async {
            self.saveData()
            print("Data from Excel saved")
        }
    }
    
    
    //MARK: - SaveData to the Realm
    
    func saveData() {
        
        do {
            try realm.write {
                for item in currentString {
                    let newItem = FunctionData()
                    newItem.functionName = item
                    realm.add(newItem)
                }
            }
        } catch {
            print ("Error trying to Realm data, \(error)")
        }
    }
    
}

How can I make a filter of something, to make that the App just save the Information from Excel ones? Thanks a lot for the help!

1

There are 1 answers

2
Виктор Слободян On

Ok, I think it doesn't work with UUID(), because it will be different all time.

let filter = // choose what you need
if let items = Array(realm.objects(FunctionData.self).filter("parameterName == %@", filter)) {
     // Do not save
} else {
     // Save
}

And try to use realm.add(newItem, update: .modified) for saving