RP89
RP89

Reputation: 121

Observing the changes to Object Swift 4

I have Swift object with about 20 Properties. In the app, there is a screen to get the user input and create the above swift object from the user entered value. Right now, if the user clicks the back button, all the user entered data will lose. So I want to alert the user to save the details if he/she has made any changes. How do we identify if the user has made any changes to the properties. Is it possible to use KVO in this case as we have too many properties?

Upvotes: 2

Views: 1044

Answers (2)

Rakesha Shastri
Rakesha Shastri

Reputation: 11242

What you need is a data model to hold the information in that particular screen, and then compare it with the original data when leaving the screen.

For the sake of simplicity, let's assume your screen has 2 text fields. One holds a name and another the age of a person.

struct Person: Equatable {
    var name: String
    var age: Int
}

When you first open this screen, the model will have the default values. Create a copy of this model and whenever the user makes any changes to the values on the screen, update the copy.

class YourViewController: UIViewController {
    // Populate these 2 values when creating your view controller
    var person: Person!
    var personCopy: Person!

    .
    .
    .

    // You need to add this target to your text fields
    @objc func textFieldDidChange(_ textField: UITextField) {
        switch textField {
        case personTextField:
            personCopy.name = personTextField.text!
        case ageTextField:
            personCopy.age = Int(ageTextField.text!)!
        default:
            // Handle other text fields here or write separate cases for them
    }

    func dismissView() {
        if person == personCopy {
            // Dismiss your view
        } else {
            // Show alert
        }
    }

}

If the user presses the back button, all you need to do is compare these 2 models and check if they are the same. If they are the same, you can go back, if not, prompt an alert asking the user to save changes or discard.

Upvotes: 3

Super Geroy
Super Geroy

Reputation: 123

I think KVO would be overkill here. Use KVO only for distant objects in your app. Here you have the UITextFields in your viewController and you must have reference to the user object anyway.

Easier is: On the back button press you would check all text properties of your UITextField objects to the (existing) values of your user object. If one of them has changed then present the alert.

Upvotes: 0

Related Questions