1

I have a testing case in Swift trying to wait for a property change:

    import XCTest

class AsynchronyousKVOTests: XCTestCase {

    let testedObject : TestedObjet = TestedObjet.init()

    func testKeyValueObservingExpectationForObject() {

        // 1st approach, fails:
        keyValueObservingExpectationForObject(self.testedObject, keyPath: "testedProperty") { object, changes in

            return true // Breakpoint never reached!
        }

        // 2nd approach, also fails:
        keyValueObservingExpectationForObject(self.testedObject, keyPath: "testedProperty", expectedValue: "After")

        self.testedObject.updateTestedPropertyAsynchronyously("After")
        // Expectation not fullfilled
        waitForExpectationsWithTimeout(2, handler: nil)
    }
}

class TestedObjet : NSObject {

    var testedProperty : NSString = "Before"

    func updateTestedPropertyAsynchronyously(value: NSString) {

        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), {
            sleep(1)
            dispatch_sync(dispatch_get_main_queue(), {
                self.testedProperty = value
        })
        })
    }

}

Why testKeyValueObservingExpectationForObject handler block is never called?

enter image description here

4

1 回答 1

2

您必须使用以下关键字在 Swift 中启用键值观察dynamic

dynamic var testedProperty: NSString = "Before"
于 2016-03-11T06:47:02.320 回答