Skip to content

Instantly share code, notes, and snippets.

@alfian0
Created February 3, 2020 09:31
Show Gist options
  • Save alfian0/7f9bb24d7cb665b4ce0069ce24ae9aa0 to your computer and use it in GitHub Desktop.
Save alfian0/7f9bb24d7cb665b4ce0069ce24ae9aa0 to your computer and use it in GitHub Desktop.
KVO implementation swift
import Foundation
class User: NSObject {
@objc dynamic var name: String?
init(with name: String) {
super.init()
self.name = name
}
}
private var myContext = 0
class UserManager: NSObject {
var user: User
init(with user: User) {
self.user = user
super.init()
self.user.addObserver(self, forKeyPath: #keyPath(User.name), options: .new, context: &myContext)
}
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
guard context == &myContext else {
super.observeValue(forKeyPath: keyPath, of: object, change: change, context: &myContext)
return
}
print("alfian", change?[NSKeyValueChangeKey.newKey] ?? "empty")
}
deinit {
self.user.removeObserver(self, forKeyPath: #keyPath(User.name), context: &myContext)
}
}
var newUser = User(with: "Alfian")
var manager = UserManager(with: newUser)
newUser.name = "asd"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment