r4id4
r4id4

Reputation: 6077

Realm Swift design pattern

I'm currently using the following flow in my app:

So the first thing I do is to query Realm and populate the UITableView.
When a row is clicked the UIViewController is presented to show more details, which are contained in my previously-queried Realm Object. Therefore I pass the object in the following way

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        let destinationVC = segue.destination as! UIViewController
        destinationVC.rowData = selectedRowData
        }

where selectedRowData is the Realm Object corresponding to the selected row.
Now, UIViewController allows the user to update some properties, which have to be stored in my Realm instance upon a Save action. That being said I cannot simply update the Realm Object on the go as

rowData.myCustomProperty = newCustomPropertyUpdatedByTheUser

otherwise Realm throws an exception saying I tried to perform a write outside a write statement. Obviously I do not want to perform a write at this time, otherwise if the user negates the operation (e.g. by getting back to the UITableViewController) I would have the value stored regardless, which is bad.
I was wondering then what's the best solution/pattern to be used in this case that makes me avoid replication of code as much as possible.
A solution that came to my mind is to store temporarily the values in some variables/struct and then update rowData when the save button is clicked.
It works but I personally don't like this solution, e.g. if you update the data model you will have to keep the structure consistent etc, so if you have a better design pattern please share.

Upvotes: 0

Views: 306

Answers (1)

Scrungepipes
Scrungepipes

Reputation: 37581

When your view controller launches at that point start a transaction with realm. If you wish to save the changes then commit that transaction, if the user goes back to the without saving then don't commit the transaction.

Upvotes: 0

Related Questions