@@ -98,6 +98,60 @@ class QueryTests: XCTestCase {
9898 query [ " b " ] = nil
9999 XCTAssertNil ( query [ " b " ] )
100100 }
101+
102+ // MARK: KVO
103+
104+ func testKVO( ) {
105+ let query = Query ( )
106+ query. addObserver ( self , forKeyPath: " hitsPerPage " , options: [ . new, . old] , context: nil )
107+ query. addObserver ( self , forKeyPath: " attributesToRetrieve " , options: [ . new, . old] , context: nil )
108+ defer {
109+ query. removeObserver ( self , forKeyPath: " hitsPerPage " )
110+ query. removeObserver ( self , forKeyPath: " attributesToRetrieve " )
111+ }
112+ query. hitsPerPage = 666
113+ query. hitsPerPage = 666 // setting the same value again should not trigger any call
114+ query. hitsPerPage = nil
115+ query. attributesToRetrieve = [ " abc " , " xyz " ]
116+ query. attributesToRetrieve = [ " abc " , " xyz " ] // setting the same value again should not trigger any call
117+ query. attributesToRetrieve = nil
118+ XCTAssertEqual ( 4 , iteration)
119+ }
120+
121+ /// Tracks the number of calls to `observeValue(forKeyPath:of:change:context:)`.
122+ var iteration : Int = 0
123+
124+ override func observeValue( forKeyPath keyPath: String ? , of object: Any ? , change: [ NSKeyValueChangeKey : Any ] ? , context: UnsafeMutableRawPointer ? ) {
125+ iteration += 1
126+ switch iteration {
127+ case 1 :
128+ XCTAssertEqual ( keyPath, " hitsPerPage " )
129+ let old = change![ . oldKey] as? Int
130+ let new = change![ . newKey] as? Int
131+ XCTAssert ( nil == old)
132+ XCTAssertEqual ( 666 , new)
133+ case 2 :
134+ XCTAssertEqual ( keyPath, " hitsPerPage " )
135+ let old = change![ . oldKey] as? Int
136+ let new = change![ . newKey] as? Int
137+ XCTAssertEqual ( 666 , old)
138+ XCTAssert ( nil == new)
139+ case 3 :
140+ XCTAssertEqual ( keyPath, " attributesToRetrieve " )
141+ let old = change![ . oldKey] as? [ String ]
142+ let new = change![ . newKey] as? [ String ]
143+ XCTAssert ( nil == old)
144+ XCTAssertEqual ( [ " abc " , " xyz " ] , new!)
145+ case 4 :
146+ XCTAssertEqual ( keyPath, " attributesToRetrieve " )
147+ let old = change![ . oldKey] as? [ String ]
148+ let new = change![ . newKey] as? [ String ]
149+ XCTAssertEqual ( [ " abc " , " xyz " ] , old!)
150+ XCTAssert ( nil == new)
151+ default :
152+ XCTFail ( " Unexpected call to `observeValue(forKeyPath:of:change:context:)` " )
153+ }
154+ }
101155
102156 // MARK: High-level
103157
0 commit comments