Created
April 13, 2016 01:24
-
-
Save z3bi/47b31af81bf7fe7398f50ec0f80bd089 to your computer and use it in GitHub Desktop.
This file contains 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
class ViewController: UIViewController { | |
override func viewDidLoad() { | |
super.viewDidLoad() | |
let user = User() | |
let name1 = Name() | |
name1.first = "bob" | |
let name2 = Name() | |
name2.first = "john" | |
user.name = name1 | |
user.name = name2 | |
name2.first = "dude" | |
} | |
} | |
class Name: NSObject { | |
dynamic var first: NSString? | |
dynamic var last: NSString? | |
} | |
class User: NSObject { | |
private var kvoContextName: UInt8 = 1 | |
var name: Name? { | |
didSet(oldName) { | |
print("did set") | |
if let oldName = oldName { | |
print("removing") | |
oldName.removeObserver(self, forKeyPath: "first") | |
} | |
if let name = name { | |
print("adding") | |
name.addObserver(self, forKeyPath: "first", options: NSKeyValueObservingOptions.New, context: &kvoContextName) | |
} | |
} | |
} | |
override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) { | |
if context == &kvoContextName { | |
print("observed") | |
} | |
} | |
deinit { | |
print("goodbye") | |
if let name = name { | |
name.removeObserver(self, forKeyPath: "first") | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment