Swift 3: Own Observer for Singleton

I wonder if there is a way to observe a single class for changes in the ony of its property

In my case with Realm, I have something like this

class User: Object {
   dynamic var name:String = ""
   dynamic var email:String = ""
   dynamic var id:String = ""
   dynamic var picURL:String = ""
   dynamic var pic:Data = Data()

    static let currentUser = User()
    {
        didSet
        {
            try! realm.write {
                realm.add(currentUser, update: true)
            }
    }
  }
}

What I want to achieve, I want to have only one user object in my application, and at any time, when any of its properties are changed, I would like to save it in Realm.

However, the example above shows the error that

'let' declarations cannot observe properties

How would you approach him? Do you think my idea of ​​using a Realm singleton object and updating it anytime with some property changes is a good idea?

I wonder if it really makes sense to have a singleton class object that is stored in Realm.

+3
3

Realm Object, , Realm GitHub, , .

Alcivanio , , , Realm. , Realm , didSet , Realm. .

: singleton Realm Object, . , update, Realm, Singleton .

, didSet , let, Objective-C .

, , :

fileprivate var _current: User? = nil

class User: Object {
    dynamic var name:String = ""
    dynamic var email:String = ""
    dynamic var id:String = ""
    dynamic var picURL:String = ""
    dynamic var pic:Data = Data()

    static var current: User
    {
        if _current == nil {
            let realm = try! Realm()

            // Query for an existing user
            _current = realm.objects(User.self).first

            // Create a new user if it didn't exist in Realm
            if _current == nil {
                 _current = User()
                 try! realm.write { realm.add(_current) }
            }
        }
        return _current
    }

    public func update(_ block: (() -> Void)) {
        let realm = try! Realm()
        try! realm.write(block)
    }
}

let user = User.current
user.update {
    user.name = "DCDC"
}
+1

, , , . .

dynamic var name: String {
    didSet{
        User.updateOnRealm()//create this method
    }
}

, -

class func updateOnRealm() {
    //update code here
}
+1

, :

, , , - , Realm.

:

  • class User, Singleton.

  • class UserManager, Singleton

  • A . WITH . INPUT ( ..).

With this approach, you can easily test your class User, extend it, subclass and reuse.

If you need a comment on the code snippets below =).

0
source

Source: https://habr.com/ru/post/1668244/


All Articles