본문 바로가기
Programming/ios

add multi addObserver for KVO

by guru_k 2017. 7. 16.
728x90
반응형

using addObserver function to observe one or more specific values, should be able to separate values.


ex. If we have Label1 and Label2, we don't know what is Label1's value in observeValue function.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// define two UILabel
@IBOutlet var label1: UILabel!
@IBOutlet var label2: UILabel!
 
// add addObserver to each label
label1.addOberver(self, forKeyPath: "text", options: [.old, .new], context: nil)
label2.addOberver(self, forKeyPath: "text", options: [.old, .new], context: nil)
 
// value watch through observeValue
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
    if keyPath == "text" {
        print("old text : ", change?[.oldKey])
        print("new text : ", change?[.newKey])
    }
}
cs


In above observeValue, It is hard to know what is label1's value.


To solve this problem, we can use context parameter in addObserver.


context means Arbitrary data that is passed to observer in.


Using context parameter, we can solve this problem.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
// label1, label2 data for context
private static var label1 = 0
private static var label2 = 1
 
// define two UILabel
@IBOutlet var label1: UILabel!
@IBOutlet var label2: UILabel!
 
// add context argument data 
label1.addOberver(self, forKeyPath: "text", options: [.old, .new], context: &MyClass.label1)
label2.addOberver(self, forKeyPath: "text", options: [.old, .new], context: &MyClass.label2)
 
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
    // using context value, classify each label's value
    if context == &label1 {
        print("old label1 text : ", change?[.oldKey])
        print("new label1 text : ", change?[.newKey])
    } else if context == &label2 {
        print("old label2 text : ", change?[.oldKey])
        print("new label2 text : ", change?[.newKey])    
    } 
}
cs


728x90
반응형

댓글