2016-03-10 29 views
1

我在斯威夫特測試情況下試圖等待一個屬性變化:keyValueObservingExpectationForObject處理塊不叫

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 
     }) 
     }) 
    } 

} 

爲什麼testKeyValueObservingExpectationForObject處理程序塊從不叫什麼名字?

enter image description here

回答

1

您必須啓用斯威夫特鍵值觀察與dynamic關鍵字:

dynamic var testedProperty: NSString = "Before" 
+0

有趣的是Objective-C的性質並不需要'動態」關鍵字。 – Lukasz

+1

我懷疑是可觀察的是昂貴的(覆蓋設置並獲得)。因此,明確表示是一件好事。 –