user2996025 user2996025 - 1 year ago 49
Swift Question

While loop condition not reevaluating

My video player selects and plays a given cell.
My goal is to wait until another video is played to proceed in the code.

while app.tables.elementBoundByIndex(0).cells.elementBoundByIndex(0).selected {}

Somehow, in the while loop, the reevaluation does not happen (when the cell is not selected anymore: cell.selected -> true), but when placing a breakpoint and checking manually in debugger, then cell.selected -> false

Answer Source

Running checks on the view hierarchy in a while loop does not cause the view hierarchy to be updated between each loop. The check will be made against a cached version of the view hierarchy, which will not be updated unless you interact with the app.

To ensure that the view hierarchy is updated for each check, you should use expectationForPredicate:evaluatedWithObject:handler: and waitForExpectationsWithTimeout:handler:.

class MyTestCase: XCTestCase {
    let cell = app.tables.elementBoundByIndex(0).cells.elementBoundByIndex(0)
    let notSelectedPredicate = NSPredicate(format: "selected == false")
    expectationForPredicate(notSelectedPredicate, evaluatedWithObject: cell, handler: nil)
    waitForExpectationsWithTimeout(10, handler: nil)
    // proceed with the test...

This way, the view hierarchy to check against will be refreshed for each check.