Created
February 3, 2020 09:31
-
-
Save alfian0/7f9bb24d7cb665b4ce0069ce24ae9aa0 to your computer and use it in GitHub Desktop.
KVO implementation swift
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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